Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. A string is valid if brackets are closed in the correct order by the same type, and every closing bracket has a corresponding opening bracket of the same type.
Use a stack data structure. Iterate through each character. If it's an opening bracket, push it onto the stack. If it's a closing bracket, check if the stack is empty or if the top of the stack doesn't match the corresponding opening bracket — if either is true, return false. After processing all characters, return true if the stack is empty.
This classic problem tests understanding of stack-based parsing. Time complexity is O(n) and space complexity is O(n) for the stack in the worst case.
Example Input & Output
Simple parentheses balanced
Incorrect nesting
Empty string
Multiple bracket types
Mismatched brackets
Algorithm Flow

Solution Approach
Best Answers
class Solution {
public boolean solution(String s) {
java.util.Stack<Character> st=new java.util.Stack<>();
for(int i=0;i<s.length();i++){char c=s.charAt(i);
if(c=='('||c=='{'||c=='[')st.push(c);
else if(st.isEmpty())return false;
else if(c==')'&&st.pop()!='(')return false;
else if(c=='}'&&st.pop()!='{')return false;
else if(c==']'&&st.pop()!='[')return false;
}return st.isEmpty();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
