20.有效的括号
class Solution:
def isValid(self, s: str) -> bool:
list = []
dic = {"(":")", "[":"]", "{":"}"}
for i in s:
if i in '([{':
list.append(i)
else:
if len(list) == 0:
return False
a = list.pop(-1)
if dic[a] != i:
return False
if len(list) != 0:
return False
return True
遍历输入的字符串,判断是否是左括号,如果是将其加入到列表中。如果不是,判断列表是否为空,如果为空,返回False,否则将列表的最后一个元素取出来,再建立一个字典(对应括号),若取出来的元素没有对应的字典元素,返回False。最后判断一下列表是否为空。
155.最小栈
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.list = []
def push(self, x: int) -> None:
self.list.append(x)
def pop(self) -> None:
self.list.pop(-1)
def top(self) -> int:
return self.list[-1]
def getMin(self) -> int:
return min(self.list)
# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(x)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()
使用列表的添加删除索引和取最小值的操作
224.基本计算器
class Solution:
def calculate(self, s: str) -> int:
list = []
sign = 1
res = 0
num = 0
for i in s:
if i == '(':
list.append(res)
list.append(sign)
res = 0
sign = 1
num = 0
elif i == ')':
res += num*sign
sign = list.pop()
res = list.pop() + res*sign
num = 0
sign = 1
elif i == '+':
res += num*sign
num = 0
sign = 1
elif i == '-':
res += num*sign
num = 0
sign = -1
elif i != ' ':
num = num*10 + int(i)
res = res + num*sign
return res
如果当前是(,那么说明后面的小括号里的内容需要优先计算,所以要把res,sign进栈,更新res和sign为新的开始;
如果当前是),那么说明当前括号里的内容已经计算完毕,所以要把之前的结果出栈,然后计算整个式子的结果;
如果当前是操作符+或者-,那么需要更新计算当前计算的结果res,并把当前数字num设为0,sign设为正负,重新开始;
最后,当所有数字结束的时候,需要把结果进行计算,确保结果是正确的。
232.用栈实现队列
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.list1 = []
self.list2 = []
def push(self, x: int) -> None:
"""
Push element x to the back of queue.
"""
self.list1.append(x)
def pop(self) -> int:
"""
Removes the element from in front of queue and returns that element.
"""
if len(self.list2) != 0:
return self.list2.pop()
else:
while len(self.list1) != 0:
self.list2.append(self.list1.pop())
return self.list2.pop()
def peek(self) -> int:
"""
Get the front element.
"""
if len(self.list2) != 0:
return self.list2[-1]
else:
while len(self.list1) != 0:
self.list2.append(self.list1.pop())
return self.list2[-1]
def empty(self) -> bool:
"""
Returns whether the queue is empty.
"""
return self.list1 == self.list2 == []
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
使用两个栈,将list1中的元素全部pop到(并添加到list2),然后从list2中pop或peek出
496.下一个更大元素 I
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
list = []
for i in nums1:
b = 1
a = nums2.index(i)
for j in nums2[a+1:]:
if i < j:
list.append(j)
b = 0
break
if b == 1:
list.append(-1)
return list
遍历循环,循环第一个列表,存下第二个列表中与第一个列表相同数的索引,然后根据此索引开始遍历循环第二个列表,比较两数的大小,将大的值添加到一个新的列表中。
682.棒球比赛
class Solution:
def calPoints(self, ops: List[str]) -> int:
i = 0
list = []
while i < len(ops):
if ops[i] == 'C':
list.pop()
elif ops[i] == '+':
list.append(list[-1] + list [-2])
elif ops[i] == 'D':
list.append(list[-1] * 2)
else:
list.append(int(ops[i]))
i += 1
return sum(list)
建立一个列表,循环,当是数字,将其加入到列表中,然后根据题目意思执行各种操作,把结果都加入到列表中,最后对列表进行求和。
844.比较含退格的字符串
class Solution:
def backspaceCompare(self, S: str, T: str) -> bool:
list1 = []
list2 = []
for i in S:
if i != '#':
list1.append(i)
elif list1:
list1.pop()
for j in T:
if j != '#':
list2.append(j)
elif list2:
list2.pop()
return list1 == list2
建立两个列表,遍历循环字符串,把不是‘#’的加入到列表中,注意第一位如果是‘#’,不能pop()。
最后比较两个列表。