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
Check if a string containing only parentheses '()' is balanced. Use a counter: increment for '(', decrement for ')'. If the counter ever goes negative, return false. If the counter is zero at the end, the string is balanced.
A negative count means more closing than opening parentheses at that point, which cannot be fixed later. A non-zero count at the end means unclosed opening parentheses remain.
Time complexity is O(n), space complexity is O(1).
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.
