题目
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()"
输出: true
思路
- 判断边界条件
- 使用数据结构栈,如果是左边,则将右边进栈
- 遍历到下个字符,出栈比较 ,不符则返回false
- 遍历结束,如果栈为空,则为true
核心代码: 判断是否为有效括号
else { if (stack.isEmpty() || stack.pop() != ch) { return false; } }
class Solution {
public boolean isValid(String s) {
if (s == null || s.length() == 0) return true;
Stack<Character> stack = new Stack<>();
for (Character ch : s.toCharArray()) {
if (ch == '(') {
stack.push(')');
} else if (ch == '[') {
stack.push(']');
} else if (ch == '{') {
stack.push('}');
} else {
if (stack.isEmpty() || stack.pop() != ch) {
return false;
}
}
}
return stack.isEmpty();
}
}