def is_valid(s):
stack=[]; m={')':'(','}':'{',']':'['}
for c in s:
if c in m:
if not stack or stack[-1]!=m[c]: return False
stack.pop()
else: stack.append(c)
return not stack
public boolean isValid(String s){
Stack<Character> st=new Stack<>();
for(char c:s.toCharArray()){
if(c=='('||c=='{'||c=='[') st.push(c);
else{
if(st.isEmpty()) return false;
char t=st.pop();
if((c==')'&&t!='(')||(c=='}'&&t!='{')||(c==']'&&t!='[')) return false;
}
} return st.isEmpty();
}
Python dict mapping cleaner. 'not stack' works — empty list is falsy.
def is_valid(s):
stack=[]; m={')':'(','}':'{',']':'['}
for c in s:
if c in m:
if not stack or stack[-1]!=m[c]: return False
stack.pop()
else: stack.append(c)
return not stack
public boolean isValid(String s){
Stack<Character> st=new Stack<>();
for(char c:s.toCharArray()){
if(c=='('||c=='{'||c=='[') st.push(c);
else{
if(st.isEmpty()) return false;
char t=st.pop();
if((c==')'&&t!='(')||(c=='}'&&t!='{')||(c==']'&&t!='[')) return false;
}
} return st.isEmpty();
}
1. Opening: push 2. Closing: check top 3. Return empty