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.
Example:
Given "((", return false. Given "{()[]}", return true. Given "{]", return false. Given "]", return false.
class Solution {
public boolean isValid(String s) {
if(!isOdd(s.length()))
return false;
else{
if(s.length() == 0)
return true;
else{
char[] c = s.toCharArray();
char[] temp = new char[s.length()];
int j = 0;
for(int i=0;i<s.length();i++){
if(c[i]=='{' || c[i]=='[' || c[i]=='('){
temp[j] = c[i];
j++;
}
if(c[i]=='}' || c[i]==']' || c[i]==')'){
if(j==0)
return false;
else{
if(!isPair(temp[j-1],c[i]))
return false;
else{
j--;
}
}
}
}
if(j == 0)
return true;
else
return false;
}
}
}
public boolean isOdd(int num){
if(num % 2 != 0)
return false;
else
return true;
}
public boolean isPair(char pre, char next){
switch(pre){
case '{':
if(next == '}')
return true;
else
return false;
case '[':
if(next == ']')
return true;
else
return false;
case '(':
if(next == ')')
return true;
else
return false;
default:
return false;
}
}
}