Skip to content

Commit 7eae790

Browse files
committed
feat: solve valid parantheses
1 parent b115010 commit 7eae790

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

valid-parentheses/GangBean.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
class Solution {
2+
public boolean isValid(String s) {
3+
/**
4+
1. understanding
5+
- given string contains character which has paired characters.
6+
- validate all given characters in input string has each pair, and valid in order.
7+
2. strategy
8+
- use stack, to save left brackets, and if you encounter right bracket, then pop from stack, and compare two characters are paired.
9+
- if not paired on any right character, or stack is empty then return false.
10+
- all characters are iterated and stack is not empty, then return false.
11+
3. complexity
12+
- time: O(N), N is the length of input string s.
13+
- space: O(N), for stack variable memory.
14+
*/
15+
Stack<Character> leftBracket = new Stack<>();
16+
for (char c : s.toCharArray()) {
17+
if (c == '(' || c == '{' || c == '[') {
18+
// when character is left bracket, then push to stack.
19+
leftBracket.push(c);
20+
} else if (c == ')' || c == '}' || c == ']') {
21+
if (leftBracket.isEmpty()) return false;
22+
char left = leftBracket.pop();
23+
if (isPair(left, c)) continue;
24+
return false;
25+
} else {
26+
throw new RuntimeException(String.format("Not valid input character: %c in input %s", c, s));
27+
}
28+
}
29+
return leftBracket.isEmpty();
30+
}
31+
32+
private boolean isPair(char left, char right) {
33+
return (left == '(' && right == ')')
34+
|| (left == '{' && right == '}')
35+
|| (left == '[' && right == ']');
36+
}
37+
}
38+

0 commit comments

Comments
 (0)