forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20-Valid-Parentheses.java
More file actions
24 lines (23 loc) · 895 Bytes
/
20-Valid-Parentheses.java
File metadata and controls
24 lines (23 loc) · 895 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
class Solution {
public boolean isValid(String s) {
if (s.length() % 2 != 0) return false;
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (
stack.isEmpty() &&
(s.charAt(i) == ')' || s.charAt(i) == '}' || s.charAt(i) == ']')
) return false; else {
if (!stack.isEmpty()) {
if (
stack.peek() == '(' && s.charAt(i) == ')'
) stack.pop(); else if (
stack.peek() == '{' && s.charAt(i) == '}'
) stack.pop(); else if (
stack.peek() == '[' && s.charAt(i) == ']'
) stack.pop(); else stack.add(s.charAt(i));
} else stack.add(s.charAt(i));
}
}
return stack.isEmpty();
}
}