Created
December 27, 2012 20:23
-
-
Save zac-xin/4391624 to your computer and use it in GitHub Desktop.
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
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) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
if(s == null || s.length() == 0) | |
return true; | |
if(s.length() % 2 == 1) | |
return false; | |
Stack<Character> stack = new Stack<Character>(); | |
HashSet<Character> rightPars = new HashSet<Character>(); | |
rightPars.add(')'); | |
rightPars.add('}'); | |
rightPars.add(']'); | |
char arr[] = s.toCharArray(); | |
for(int i = 0; i < s.length(); i++){ | |
char c = arr[i]; | |
if(!rightPars.contains(c)){ | |
stack.push(c); | |
}else{ | |
if(stack.empty()) | |
return false; | |
char l = stack.pop(); | |
if( l != getLeft(c)) | |
return false; | |
} | |
} | |
if(stack.empty()) | |
return true; | |
else | |
return false; | |
} | |
public char getLeft(char right){ | |
if(right == ')') | |
return '('; | |
if(right == '}') | |
return '{'; | |
if(right == ']') | |
return '['; | |
return 'a'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment