20. Valid Parentheses

LeetCode

Approach: Stacks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public boolean isValid(String s) {
LinkedList<Character> ans=new LinkedList<>();

for(int i=0;i<s.length();i++){
if(ans.size()>0&&is_pairs(ans.peek(), s.charAt(i))){
ans.pop();
}else{
ans.push(s.charAt(i));
}
}
return ans.isEmpty();
}

public boolean is_pairs(char a, char b){
if(a=='('&&b==')') return true;
if(a=='{'&&b=='}') return true;
if(a=='['&&b==']') return true;
return false;
}
}

0%