给定一个只包括 ‘(‘,‘)‘,‘{‘,‘}‘,‘[‘,‘]‘ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
class Solution {
public boolean isValid(String s) {
if(s.length()==0){
return true;
}
if(s.length()==1){
return false;
}
Stack<Character> stack=new Stack<>();
int i=0;
stack.push(s.charAt(i));
i++;
while(i!=s.length()){
char tmp = s.charAt(i);
if(!stack.empty()){
char peek = stack.peek();
if((tmp == ‘)‘&&peek==‘(‘)||(tmp==‘]‘&&peek==‘[‘)||(tmp==‘}‘&&peek==‘{‘)){
stack.pop();
i++;
continue;
}
}
stack.push(tmp);
i++;
}
return stack.empty();
}
}
原文:https://www.cnblogs.com/gongzixiaobaibcy/p/11892555.html