Created
September 25, 2014 00:35
-
-
Save sreeprasad/6fea70a07016efc30b68 to your computer and use it in GitHub Desktop.
Valid Parenthesis Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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