-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathValid Parentheses.java
More file actions
30 lines (26 loc) · 876 Bytes
/
Valid Parentheses.java
File metadata and controls
30 lines (26 loc) · 876 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
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack();
Map<Character, Character> mapping = new HashMap<>();
mapping.put('(', ')');
mapping.put('[', ']');
mapping.put('{', '}');
for (int i = 0; i < s.length(); i++) {
char currentLetter = s.charAt(i);
if (mapping.containsKey(currentLetter)) {
stack.push(mapping.get(currentLetter));
continue;
}
char currentLetterFromStack;
try {
currentLetterFromStack = stack.pop();
} catch (Exception e) {
currentLetterFromStack = '0';
}
if (currentLetterFromStack != currentLetter) {
return false;
}
}
return stack.isEmpty();
}
}