目录结构
1.题目
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例:
输入: "()"
输出: true
输入: "()[]{}"
输出: true
输入: "(]"
输出: false
输入: "([)]"
输出: false
输入: "{[]}"
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.题解
利用栈处理。
- 当遇到左括号,直接入栈。
- 当遇到右括号,且栈顶为对应左括号,则将栈顶元素出栈;否则返回false。
- 当字符串遍历结束后,若栈为空则返回true,否则返回false。
public class Solution20 {
public boolean isValid(String s) {
if (s.length() == 0) {
return true;
}
LinkedList<Character> stack = new LinkedList<>();
for (char c : s.toCharArray()) {
switch (c) {
case '(':
case '[':
case '{':
stack.push(c);
break;
case ')':
if (!stack.isEmpty() && stack.getFirst() == '(') {
stack.pop();
} else {
return false;
}
break;
case ']':
if (!stack.isEmpty() && stack.getFirst() == '[') {
stack.pop();
} else {
return false;
}
break;
case '}':
if (!stack.isEmpty() && stack.getFirst() == '{') {
stack.pop();
} else {
return false;
}
break;
default:
break;
}
}
return stack.isEmpty();
}
}
- 时间复杂度:
- 空间复杂度: