给定一个只包括 '(',')','{','}','[',']' 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
代码如下:
class Solution {
public boolean isValid(String s) {
Stack<Character> stack=new Stack<>();
// 将字符串转为字符输出
for (int i = 0; i < s.length(); i++) {
char c=s.charAt(i);
// 碰到左括号直接入栈
if(c=='('||c=='['||c=='{'){
stack.push(c);
}else {
//此时c是个右括号
if(stack.isEmpty()){
// 右括号是第一个字符,没有相应的左括号匹配
return false;
}
// 弹出左括号
char top=stack.pop();
if(c==')'&&top!='('){
return false;
}
if(c==']'&&top!='['){
return false;
}
if(c=='}'&&top!='{'){
return false;
}
}
}
// 此时字符串已经扫描完毕,判断当前栈中是否为空
//若为空,则true,否则false
return stack.isEmpty();
}
}
实现结果: