-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path20. Valid Parentheses-Array.java
31 lines (28 loc) · 1.04 KB
/
20. Valid Parentheses-Array.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
class Solution {
public boolean isValid(String s) {
// Create array to track openning bracket(s)
char[] stack = new char[s.length()];
// This index variable represent most top data in stack
int idx = -1;
// Iterate through all char(s) in string
for (char c : s.toCharArray()) {
// Push openning bracket(s) into array
if (c == '(' || c == '{' || c == '[')
stack[++idx] = c;
// Is closed bracket(s)
else {
// Check if openning bracket is found
if (idx >= 0 &&
((stack[idx] == '(' && c == ')') ||
(stack[idx] == '{' && c == '}') ||
(stack[idx] == '[' && c == ']')))
idx--;
else
return false;
}
}
// If idx = -1, means array is empty which means all openning bracket and closed
// bracket are matches
return idx == -1;
}
}