Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#leetcode
import java.util.Stack;
public class ValidParenthesis {
public boolean isValid(String s) {
if(s == null || s.length() == 0 || s.length() % 2 == 1) return false;
Stack<Character> chars = new Stack<Character>();
int len = s.length();
for(int i = 0; i < len; i++){
char c = s.charAt(i);
if(!validCharacter(c)) return false;
if(isLeftHalf(c)) chars.push(c);
else{
if(chars.size() == 0) return false;
char top = chars.peek();
if(!match(top, c)) return false;
chars.pop();
}
}
if(chars.size() != 0) return false;
return true;
}
private boolean validCharacter(char c){
switch(c){
case '(':
case ')':
case '[':
case ']':
case '{':
case '}':
return true;
default:
return false;
}
}
private boolean isLeftHalf(char c){
switch(c){
case '(':
case '[':
case '{':
return true;
default:
return false;
}
}
private boolean match(char left, char right){
if(left == '(' && right == ')') return true;
if(left == '[' && right == ']') return true;
if(left == '{' && right == '}') return true;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment