-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathValidParentheses.java
35 lines (31 loc) · 1.08 KB
/
ValidParentheses.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
/*https://leetcode.com/problems/valid-parentheses/*/
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); ++i)
{
try{
//push open brackets
if (s.charAt(i) == '(' || s.charAt(i) == '{' || s.charAt(i) == '[')
stack.push(s.charAt(i));
//if closing brackets are same as the top opening bracket in stack, then pop from stack
else if (s.charAt(i) == ')' && stack.peek() == '(')
stack.pop();
else if (s.charAt(i) == '}' && stack.peek() == '{')
stack.pop();
else if (s.charAt(i) == ']' && stack.peek() == '[')
stack.pop();
//otherwise return false
else
return false;
}
catch(Exception e)
{
//return false for any other character
return false;
}
}
//return true if stack is empty
return stack.empty();
}
}