-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path0423. Valid Parentheses.java
More file actions
32 lines (32 loc) · 962 Bytes
/
0423. Valid Parentheses.java
File metadata and controls
32 lines (32 loc) · 962 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public class Solution {
/**
* @param s: A string
* @return: whether the string is a valid parentheses
*/
public boolean isValidParentheses(String s) {
Stack<Character> open = new Stack<>();
Stack<Character> close = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '[' || c == '{') { //opening bracket found
open.push(c);
} else {
close.push(c);
if (open.empty()) {
return false;
}
char lastOpen = open.peek();
if (lastOpen == '(' && c == ')' || lastOpen == '[' && c == ']'
|| lastOpen == '{' && c == '}') { // check if most recent opening bracket is this closing bracket's partner
open.pop();
close.pop();
} else {
return false;
}
}
}
if (open.empty() && close.empty()) { // all opening brackets found their closing partner
return true;
}
return false;
}
}