Hi, this is Shunchi!

  • Home

  • Tags0

  • Archives267

  • Categories0

  • Curricula

  • DSA

  • LeetCode_Notes

  • Interviews

  • General

  • Resume

20. Valid Parentheses

Posted on 2020-06-14 | Edited on 2021-01-22

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;
}
}

<1…151152153…267>
ShunchiZhou

ShunchiZhou

267 posts
RSS
GitHub E-Mail Gitbook Linkedin
© 2024 ShunchiZhou
Powered by Hexo v5.4.0
|
0%