声明:
因本人为AI路上的新手,文章用于辅助个人的整理记忆,理解难免有偏差之处,都是个人拙见,如给其他同僚造成困扰,还请见谅,非常非常非常欢迎私信共同讨论,共同进步
题目描述:
Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: “()”
Output: true
Example 2:
Input: “()[]{}”
Output: true
Example 3:
Input: “(]”
Output: false
Example 4:
Input: “([)]”
Output: false
Example 5:
Input: “{[]}”
Output: true
解题思路(注:此题本人参考LeetCode上同僚的解法,因本人无更好的思路,供大家一起学习,交流):
- 如题所述,只有当由这三种符号组成的各个括号在对应的位置,对应的符号时,才能算是有效
- 首先定义一个空列表,用来放置遍历整个列表中的字符时,正向的那些括号
- 当遍历进行时,遇到反向的括号,若想有效,则必与它最近的,即它前一个字符,那个正向的括号,字符要对应
- 此解法的巧妙之处在于,在判断是否对应的条件中,已经执行了删除操作,即只要出现反向的括号,如符合题目要求,则默认执行删除操作,方便下次遍历到反向括号时,还可以与它正确顺序的正向括号进行判断,避免受到干扰
- 见代码,胜却千言万语
少废话,上代码:
class Solution:
def isValid(self, s: str) -> bool:
left = ['(', '{', '[']
right = [')', '}', ']']
lt = []
for i in s:
if i in left:
lt.append(i)
elif i in right:
#如果一开始就是反向的括号,则len(lt)为0,直接返回False
if len(lt) == 0:
return False
#当在lt中的最后一个元素(lt.pop())的索引与反括号的索引不相等,
#即是不对应的符号,直接返回False
if left.index(lt.pop()) != right.index(i):
return False
return len(lt) == 0#因if语句中包含lt.pop()指令,每次执行会将最后一个元素删除,如全部是对应的,则此时len(lt)为0
时间空间复杂度:
- Runtime: 28 ms, faster than 71.64% of Python3 online submissions for Valid Parentheses.
- Memory Usage: 13 MB, less than 98.26% of Python3 online submissions for Valid Parentheses.