描述
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 ”([)]” arenot.
public static boolean solution_4_1(char[] chars){
char[] st=new char[chars.length];
int top=0;
for(int i=0;i<chars.length;i++){
if(chars[i]=='('||chars[i]=='{'||chars[i]=='['){
st[top++]=chars[i];
}
else{
--top;
if(top<0)
return false;
else{
if(chars[i]==')'){
char t=st[top];
if(t!='(')
return false;
}
if(chars[i]=='}'){
char t=st[top];
if(t!='{')
return false;
}
if(chars[i]==']'){
char t=st[top];
if(t!='[')
return false;
}
}
}
}
if (top!=0){
return false;
}
else{
return true;
}
}