这道题很简单,就是用栈的可以解决了。由于发现leetcode给出的运行时间和内存消耗并不准确(同一个答案三次提交运行时间和内存消耗都不同),所以便不在给出具体的数值了。
自己写的答案
class Solution:
def isValid(self, s: str) -> bool:
if len(s)%2==1 or len(s)==1:
return False
stack = ['0']
for item in s:
if item =='(' or item=='{' or item=='[':
stack.append(item)
continue
a = stack.pop()
if (item==')'and a=='(') or (item==']'and a=='[') or (item=='}'and a=='{'):
continue
return False
return len(stack)==1
官方的给出的答案,思路和我是相同和,只不过用了一些小技巧,比如用了字典(哈希映射)提高速度。
时间复杂度为
O
(
n
)
O(n)
O(n),其中n是字符数串s的长度。
空间复杂度:
O
(
n
+
∣
a
∣
)
O(n+|a|)
O(n+∣a∣),其中
a
a
a表示字符集,本题中字符串包含6中括号,
∣
a
∣
=
6
|a|=6
∣a∣=6。
class Solution:
def isValid(self, s: str) -> bool:
if len(s) % 2 == 1:
return False
pairs = {
")": "(",
"]": "[",
"}": "{",
}
stack = list()
for ch in s:
if ch in pairs:
if not stack or stack[-1] != pairs[ch]:
return False
stack.pop()
else:
stack.append(ch)
return not stack
另一种比较巧妙的思路,但效率不高
class Solution:
def isValid(self, s: str) -> bool:
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''