/
ValidParenthesis.java
45 lines (38 loc) · 1.19 KB
/
ValidParenthesis.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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// https://leetcode.com/problems/valid-parentheses/
class Solution {
public boolean isValid(String s) {
int a = 0, b = 0, c = 0;
Stack<Character> stack = new Stack<>();
for (char ch: s.toCharArray()) {
if (ch == '(') {
a++;
stack.push(ch);
}
if (ch == ')') {
if (stack.isEmpty()) return false;
if (stack.pop() != '(') return false;
a--;
}
if (ch == '[') {
b++;
stack.push(ch);
}
if (ch == ']') {
if (stack.isEmpty()) return false;
if (stack.pop() != '[') return false;
b--;
}
if (ch == '{') {
c++;
stack.push(ch);
}
if (ch == '}') {
if (stack.isEmpty()) return false;
if (stack.pop() != '{') return false;
c--;
}
if (a < 0 || b < 0 || c < 0) return false;
}
return a + b + c == 0;
}
}