栈的应用
20. 有效的括号
代码
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
#使用栈stack
stack = []
for item in s:
if item == "(":
stack.append(")")
elif item == "[":
stack.append("]")
elif item == "{":
stack.append("}")
elif not stack or stack[-1] != item:
return False
else:
stack.pop()
return True if not stack else False
1047. 删除字符串中的所有相邻重复项
栈的经典应用。 要知道栈为什么适合做这种类似于爱消除的操作,因为栈帮助我们记录了 遍历数组当前元素时候,前一个元素是什么。
代码
#方法一:直接使用栈
class Solution(object):
def removeDuplicates(self, s):
"""
:type s: str
:rtype: str
"""
stack = []
for item in s:
if stack and stack[-1] == item:
stack.pop()
else:
stack.append(item)
result = ''.join(stack)
return result
# 方法二,使用双指针模拟栈,如果不让用栈可以作为备选方法。
class Solution:
def removeDuplicates(self, s: str) -> str:
res = list(s)
slow = fast = 0
length = len(res)
while fast < length:
# 如果一样直接换,不一样会把后面的填在slow的位置
res[slow] = res[fast]
# 如果发现和前一个一样,就退一格指针
if slow > 0 and res[slow] == res[slow - 1]:
slow -= 1
else:
slow += 1
fast += 1
return ''.join(res[0: slow])
150. 逆波兰表达式求值
题目链接/文章讲解/视频讲解:https://programmercarl.com/0150.%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%B1%82%E5%80%BC.html