Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.
Show Similar Problems
Have you met this question in a real interview?
Yes
No
need O(n) time to go through the whole array and worst case O(n) space to store the array.
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
stack = []
for index in range(len(s)):
current_string = s[index]
if current_string == '(' or current_string == '[' or current_string == '{':
stack.append(current_string)
if current_string == ')':
if not stack or stack.pop() != '(':
return False
if current_string == ']':
if not stack or stack.pop() != '[':
return False
if current_string == '}':
if not stack or stack.pop() != '{':
return False
if stack:
return False
return True

本文介绍了一种使用栈数据结构来验证包含括号的字符串是否有效的方法。文章详细解释了如何通过遍历输入字符串并利用栈来跟踪括号的开闭情况,以此判断括号是否正确配对。
328

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



