-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidParenthesis.java
31 lines (30 loc) · 1.02 KB
/
ValidParenthesis.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
import java.util.Stack;
/*
This Method is not proper - I have used the ASCII values of the parenthesis to check so that the code is a bit less lengthy.
Also, it involves the usage of Stack class in Java - An inbuilt stack class with all the required functions.
*/
public class ValidParenthesis {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for(int i=0;i<s.length();i++)
{
char c = s.charAt(i);
if(c=='{' || c=='[' || c=='(')
stack.push(c);
else if (c=='}' || c==']' || c==')') {
if(stack.empty())
return false;
char top = stack.peek();
int diff = (int)c - (int)top;
if((top=='(' && diff==1) || diff==2)
stack.pop();
else
return false;
}
}
if(stack.empty())
return true;
else
return false;
}
}