defpop(self) -> int: if self.empty(): returnNone if self.stack_out: return self.stack_out.pop() else: for i inrange(len(self.stack_in)): self.stack_out.append(self.stack_in.pop()) return self.stack_out.pop()
defpeek(self) -> int: ans = self.pop() self.stack_out.append(ans) return ans
defempty(self) -> bool: returnnot(self.stack_in or self.stack_out)
# 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()
# Your MyStack object will be instantiated and called as such: # obj = MyStack() # obj.push(x) # param_2 = obj.pop() # param_3 = obj.top() # param_4 = obj.empty()
classSolution: defisValid(self, s: str) -> bool: stack = [] for i in s: if i == '('or i == '['or i == '{': stack.append(i) elif i == ')': ifnot stack: returnFalse elif stack[-1] != '(': returnFalse else: stack.pop() elif i == ']': ifnot stack: returnFalse elif stack[-1] != '[' : returnFalse else: stack.pop() elif i == '}': ifnot stack: returnFalse elif stack[-1] != '{' : returnFalse else: stack.pop() iflen(stack) != 0: returnFalse else: returnTrue
Leetcode1047 删除字符串中的所有相邻重复项
遍历s ,如果栈非空并且栈顶元素等于当前正在遍历元素的话
栈顶元素出栈,否则,当前正在遍历元素压入栈
遍历到最后只剩下不重复的字符
Python代码如下:
1 2 3 4 5 6 7 8 9 10
classSolution: defremoveDuplicates(self, s: str) -> str: stack = [] for i in s: if stack and stack[-1] == i: stack.pop() else: stack.append(i) return''.join(stack)
Leetcode150 逆波兰式表达求值
遇到数字则入栈;遇到运算符则取出栈顶两个数字进行计算,并将结果压入栈中
Python代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
from operator import add, sub, mul classSolution: defevalRPN(self, tokens: List[str]) -> int: op = {'+': add, '-':sub , '*':mul, '/':lambda x, y : int(x/y)} stack = [] for i in tokens: if i notin {'+', '-', '*', '/'}: # 也可以在这写stack.append(int(token)) 后面就不用那么多int()了 stack.append(i) else: num2 = int(stack.pop()) num1 = int(stack.pop()) # 第一个出来的在运算符后面 temp_num = op[i](num1, num2) stack.append(temp_num) returnint(stack.pop())
from collections import deque classMyQueue: def__init__(self): self.queue = deque() defpop(self, value): if self.queue and value == self.queue[0]: self.queue.popleft() defpush(self, value): # 不是value >= self.queue[-1] value等于队列末尾的时候不能弹出,依然要维护,因为窗口会移动的 while self.queue and value > self.queue[-1]: self.queue.pop() self.queue.append(value) deffront(self): return self.queue[0]
classSolution: defmaxSlidingWindow(self, nums: List[int], k: int) -> List[int]: que = MyQueue() res = [] for i inrange(k): que.push(nums[i]) res.append(que.front()) for i inrange(k, len(nums)): # 弹出的是窗口左端前面的那个, 所以是i-k, 错的时候写成了i-k+1 que.pop(nums[i-k]) que.push(nums[i]) res.append(que.front()) return res
Leetcode347 前K个高频元素
总共涉及3个步骤:
1、遍历nums,用一个map存储键为元素,值为对应元素出现的次数
2、对次数进行排序
3、返回top_k
Python代码如下:
1 2 3 4 5 6 7 8
classSolution: deftopKFrequent(self, nums: List[int], k: int) -> List[int]: map = {} for i inrange(len(nums)): map[nums[i]] = map.get(nums[i], 0 ) + 1 sort_map = sorted(map.items(), key = lambda x:x[1], reverse=True) top_k = [item[0] for item in sort_map[0:k]] return top_k