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.
思路:对字符串S中的每一个字符i,如果i是左括号,则入栈。如果i是右括号,首先判断stack是否为空,空则说明没有左括号,直接返回false,如果非空则弹出栈顶的字符top来作比较,如果相匹配,继续取S中的下一个字符;如果不匹配,直接返回false。当遍历完字符串S后,判断stack中是否还有字符没有得到匹配,如果stack不为空,返回false。
public class Solution {
public boolean isValid(String s) {
if(s.length()==0||s.length()==1) return false;
Stack<Character> charStack=new Stack<Character>();
for(int i=0;i<s.length();i++){
if(s.charAt(i)=='('||s.charAt(i)=='{'||s.charAt(i)=='[')
{
charStack.push(s.charAt(i));
}
else{
if(charStack.size()==0){
return false;
}
char top=charStack.pop();
if(s.charAt(i)==')'){
if(top!='(') return false;
}
else if(s.charAt(i)==']'){
if(top!='[') return false;
}
if(s.charAt(i)=='}'){
if(top!='{') return false;
}
}
}
return charStack.size()==0;
}
}版权声明:本文为linyixiao88原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。