Skip to content

Commit 1dba003

Browse files
Create 20-Valid-Parentheses.java
1 parent 76fb98f commit 1dba003

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

java/20-Valid-Parentheses.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution {
2+
public boolean isValid(String s) {
3+
if (s.length()%2!=0)
4+
return false;
5+
Stack<Character> stack = new Stack<>();
6+
for (int i = 0; i<s.length(); i++) {
7+
if (stack.isEmpty() && (s.charAt(i)==')' || s.charAt(i)=='}' || s.charAt(i)==']'))
8+
return false;
9+
else {
10+
if (!stack.isEmpty()) {
11+
if (stack.peek()=='(' && s.charAt(i)==')') stack.pop();
12+
else if (stack.peek()=='{' && s.charAt(i)=='}') stack.pop();
13+
else if (stack.peek()=='[' && s.charAt(i)==']') stack.pop();
14+
else stack.add(s.charAt(i));
15+
}
16+
else stack.add(s.charAt(i));
17+
}
18+
}
19+
return stack.isEmpty();
20+
}
21+
}

0 commit comments

Comments
 (0)