Skip to content

Instantly share code, notes, and snippets.

@sreeprasad
Created September 25, 2014 00:35
Show Gist options
  • Save sreeprasad/6fea70a07016efc30b68 to your computer and use it in GitHub Desktop.
Save sreeprasad/6fea70a07016efc30b68 to your computer and use it in GitHub Desktop.
Valid Parenthesis Test
public class Solution {
public boolean isValid(String s) {
if(s==null){
return false;
}else if( s.length()==0 ){
return true;
}else if( (s.length()%2)!=0 ){
return false;
}
Stack<Character> st = new Stack<Character>();
char [] array = s.toCharArray();
for(int i=0;i<array.length;i++){
char c = array[i];
switch(c){
case '(' :{
st.push(c);
break;
}
case '[' :{
st.push(c);
break;
}
case '{' :{
st.push(c);
break;
}
case ')' :{
if(st.isEmpty()){
return false;
}
char v = st.pop();
if( v!='(' ){
return false;
}
break;
}
case '}' :{
if(st.isEmpty()){
return false;
}
char v = st.pop();
if( v!='{' ){
return false;
}
break;
}
case ']' :{
if(st.isEmpty()){
return false;
}
char v = st.pop();
if( v!='[' ){
return false;
}
break;
}
}
}
if(!st.isEmpty()){
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment