Created
August 7, 2014 21:56
-
-
Save jingz8804/a08daa6888cdb2bd273e to your computer and use it in GitHub Desktop.
#leetcode
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
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