从键盘输入一个仅包括(,),[,],{,}共六种字符的括号串,使用栈检查其合法性
时间: 2023-10-07 21:04:22 浏览: 69
从键盘输入一串字符,分别统计其中的字母,数字字符和其他[文].pdf
思路:
使用一个栈来存储左括号,遍历输入的字符串,如果是左括号则入栈,如果是右括号则判断栈顶元素是否与其匹配,匹配则出栈,不匹配则说明不合法。
代码实现:
```python
def check_brackets(s):
stack = []
for c in s:
if c in "([{":
stack.append(c)
elif c in ")]}":
if not stack:
return False
if c == ")" and stack[-1] == "(":
stack.pop()
elif c == "]" and stack[-1] == "[":
stack.pop()
elif c == "}" and stack[-1] == "{":
stack.pop()
else:
return False
return len(stack) == 0
```
测试样例:
```python
print(check_brackets("()[]{}")) # True
print(check_brackets("([{}])")) # True
print(check_brackets("([)]")) # False
print(check_brackets("(")) # False
print(check_brackets("))")) # False
```
输出结果:
```
True
True
False
False
False
```
阅读全文