#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
英文:
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
中文:括号配对,没有配对成功的话返回False,成功返回True
举例:The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
'''
class Solution(object):
def isValid(self,s):
length = len(s)
if length & 1 or length == 0: #字符串个数为奇数/字符串为空
return False
ret = True
stack = []
left = ('{','(','[')
right = ('}',')',']')
for i in s:
if i in left:
stack.append(i)
elif i in right:
if len(stack) < 1:
ret = False
break
if stack.pop() == left[right.index(i)]:
continue
else:
ret = False
break
else:
ret = False
break
if len(stack) > 0: #有剩余的话,说明无法配对
ret = False
return ret
21 leetcode - Valid Parentheses
最新推荐文章于 2025-12-21 17:04:13 发布
本文介绍了一个简单的Python程序,用于检查包含括号的字符串是否正确闭合。通过使用栈数据结构,该程序能有效地判断括号是否按正确的顺序关闭。
330

被折叠的 条评论
为什么被折叠?



