栈——简单
496 下一个更大的元素
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
res = list()
for i in nums1:
flag = False
for j in nums2:
if i == j:
flag = True
elif flag and j > i:
res.append(j)
break
else:
res.append(-1)
return res
————————————————
版权声明:本文为CSDN博主「coordinate_blog」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_17550379/article/details/86501664
暴力法搜索
class Solution:
def nextGreaterElement(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
dic , stack = dict(), list()
for n in nums2:
while stack and stack[-1] < n:
dic[stack.pop()] = n
stack.append(n)
return [dic.get(i , -1) for i in nums1]
————————————————
版权声明:本文为CSDN博主「coordinate_blog」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_17550379/article/details/86501664
单调栈
很难想。。纠结
682 棒球比赛
class Solution(object):
def calPoints(self, ops):
"""
:type ops: List[str]
:rtype: int
"""
stack = []
for i in ops:
if i == 'D':
stack.append(stack[-1]*2)
elif i == 'C':
stack.pop()
elif i == '+':
stack.append(stack[-1]+stack[-2])
else:
stack.append(i)
return sum(stack)
自己写的的,一直过不了编译
class Solution(object):
def calPoints(self, ops):
stack = []
for op in ops:
if op == '+':
stack.append(stack[-1] + stack[-2])
elif op == 'C':
stack.pop()
elif op == 'D':
stack.append(2 * stack[-1])
else:
stack.append(int(op))
return sum(stack)
作者:LeetCode
链接:https://leetcode-cn.com/problems/baseball-game/solution/bang-qiu-bi-sai-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
官方文档比我多了一个Int(op)…
884 比较含退格的字符串
class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
stack1 = []
stack2 = []
for i in S:
if i == '#' and stack1:
stack1.pop()
stack1.append(i)
else:
stack1.append(i)
for j in T:
if j== '#' and stack2:
stack2.pop()
stack2.append(j)
else:
stack2.append(j)
return stack1 == stack2
我一直想不出来怎么判断两个“#”怎么办
class Solution:
def backspaceCompare(self, S, T):
stack_s, stack_t = [], []
for s in S:
if s != '#':
stack_s.append(s)
elif stack_s:
stack_s.pop();
for t in T:
if t != '#':
stack_t.append(t)
elif stack_t:
stack_t.pop()
return stack_s == stack_t
这个就过了…
class Solution(object):
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
stack1 = []
stack2 = []
for i in S:
if i == '#' :
stack1.pop()
else:
stack1.append(i)
for j in T:
if j== '#':
stack2.pop()
else:
stack2.append(j)
return stack1 == stack2
这个不行
总结:神奇的ELSE 和ELIF 的区别
调BUG神器