题目如下:
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.
分析:这是关于栈的操作,可以遍历该String字符串,如果碰到左括号,则将该字符入栈,并将指针上移一位,如果碰到右括号,则比较此时的指针所指向的括号类型是否和该右括号类型匹配,如匹配,则出栈(指针下移一位),如不匹配,则直接返回false,循环完毕后,如果指针此时没有指向栈底,则返回false,否则true。
Java解题:
public static isValid(String s) {
char[] stack = new char[s.length()+1];
char[] ch = s.toCharArray();
int point=0;
for(int i=0;i<ch.length;i++){
if(ch[i]=='('||ch[i]=='['||ch[i]=='{'){
stack[++point]=ch[i];
}
else if(ch[i]==')'){
if(stack[point]=='(')
point--;
else
return false;
}
else if(ch[i]==']'){
if(stack[point]=='[')
point--;
else
return false;
}
else if(ch[i]=='}'){
if(stack[point]=='{')
point--;
else
return false;
}
}
if(point==0)
return true;
return false;
}