数据结构-栈的应用利用栈判断字符串括号是否匹配
时间: 2023-11-07 08:56:53 浏览: 101
算法步骤:
1.创建一个空栈
2.遍历字符串中的每个字符
3.如果当前字符是左括号,将其压入栈中
4.如果当前字符是右括号,检查栈是否为空,如果为空,则说明右括号没有匹配的左括号,返回false;如果栈不为空,弹出栈顶元素,检查它是否与当前右括号匹配,如果不匹配,则返回false
5.遍历完字符串后,检查栈是否为空,如果为空,则说明所有括号都匹配,返回true;否则,说明有左括号没有匹配的右括号,返回false
代码实现:
```python
def is_valid_parentheses(s: str) -> bool:
stack = []
for c in s:
if c == '(' or c == '[' or c == '{':
stack.append(c)
elif c == ')':
if not stack or stack.pop() != '(':
return False
elif c == ']':
if not stack or stack.pop() != '[':
return False
elif c == '}':
if not stack or stack.pop() != '{':
return False
return not stack
```
示例:
```python
assert is_valid_parentheses('()') == True
assert is_valid_parentheses('()[]{}') == True
assert is_valid_parentheses('(]') == False
assert is_valid_parentheses('([)]') == False
assert is_valid_parentheses('{[]}') == True
```