Skip to content

Commit bd19c48

Browse files
committed
feat : valid-parentheses
1 parent 4119a96 commit bd19c48

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

valid-parentheses/ekgns33.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/**
2+
input : string s contains just (, ), {, }, [, ]
3+
output : return if s is valid
4+
valid means that parentheses are matched(balanced)
5+
example
6+
((())) : valid
7+
(((())) : invalid
8+
{() : invalid
9+
10+
constraint :
11+
1) input string can be empty string?
12+
nope. at least one character >> if length is odd number return false
13+
edge:
14+
1) if the length of string is odd number return false
15+
16+
solution 1)
17+
ds : stack
18+
algo : x
19+
iterate through the string s
20+
if opening bracket, add to stack
21+
else check the top element of stack
22+
if matched pop
23+
else return false;
24+
return false
25+
26+
tc : O(n)
27+
sc : O(n) worst case : every character is opening bracket
28+
29+
*/
30+
class Solution {
31+
public boolean isValid(String s) {
32+
//edge
33+
if(s.length() % 2 == 1) return false;
34+
// we can use deque instead
35+
Stack<Character> stack = new Stack<>();
36+
37+
for(char c : s.toCharArray()) {
38+
if(c == '(' || c == '{' || c == '[') {
39+
stack.push(c);
40+
} else {
41+
if(stack.isEmpty()) return false;
42+
if(c == ')') {
43+
if(stack.peek() != '(') return false;
44+
} else if (c == '}') {
45+
if(stack.peek() != '{') return false;
46+
} else if (c == ']'){
47+
if(stack.peek() != '[') return false;
48+
}
49+
stack.pop();
50+
}
51+
}
52+
return stack.isEmpty();
53+
}
54+
}

0 commit comments

Comments
 (0)