-
Notifications
You must be signed in to change notification settings - Fork 0
/
20.java
25 lines (21 loc) · 867 Bytes
/
20.java
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
// Runtime: 2 ms, faster than 61.00% of Java online submissions for Valid Parentheses.
// Memory Usage: 34.2 MB, less than 100.00% of Java online submissions for Valid Parentheses.
import java.util.HashMap;
class Solution {
public boolean isValid(String s) {
HashMap<Character, Character> openCloseMap = new HashMap<>();
openCloseMap.put('(', ')');
openCloseMap.put('{', '}');
openCloseMap.put('[', ']');
Stack<Character> parenthesis = new Stack<>();
for (Character c : s.toCharArray()) {
if (openCloseMap.containsKey(c)) {
parenthesis.push(openCloseMap.get(c));
} else {
if (parenthesis.size() == 0 || !parenthesis.pop().equals(c))
return false;
}
}
return parenthesis.size() == 0;
}
}