Created
March 1, 2014 00:05
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
/* | |
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. | |
*/ | |
public class Solution { | |
public boolean isValid(String s) { | |
if (s==null || s.length()==0){ | |
return true; | |
} | |
Stack<Character> checker=new Stack<Character>(); | |
int i=0; | |
while (i<s.length()){ | |
if (s.charAt(i)=='(' || s.charAt(i)=='[' || s.charAt(i)=='{'){ | |
checker.push(s.charAt(i)); | |
i++; | |
} | |
else if (s.charAt(i)==')' || s.charAt(i)==']' || s.charAt(i)=='}'){ | |
if (checker.isEmpty()){ | |
return false; | |
} | |
else{ | |
char temp=checker.peek(); | |
if (isPair(temp, s.charAt(i))){ | |
checker.pop(); | |
i++; | |
} | |
else{ | |
return false; | |
} | |
} | |
} | |
else{ | |
return false; | |
} | |
} | |
if (checker.isEmpty() ){ | |
return true; | |
} | |
return false; | |
} | |
// check is given two chars are pair | |
private boolean isPair(char c1, char c2){ | |
String validChars="()[]{}"; | |
int indexC1=validChars.indexOf(c1); | |
int indexC2=validChars.indexOf(c2); | |
if (indexC1<0||indexC2<0){ | |
return false; | |
} | |
if (indexC1+1==indexC2){ | |
return true; | |
} | |
return false; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment