每日一題之LeetCode 棧簡單題集合496,682,232,225,155,844,20
496 下一個最大的元素
方法1 :自己瞎寫的 沒有考慮到棧的特性
class Solution:
def nextGreaterElement(self, nums1, nums2):
L=[] for i in nums1: k=nums2.index(i) lenth2=len(nums2) if k==lenth2-1: L.append(-1) for j in range(k+1,lenth2): if nums2[j]>i: L.append(nums2[j]) break if j==lenth2-1: L.append(-1) return L
方法2:網上大神寫的 很膜拜
class Solution:
def nextGreaterElement(self, nums1, nums2):
d = {} st = [] ans = [] for x in nums2: while len(st) and st[-1] < x: d[st.pop()] = x st.append(x) for x in nums1: ans.append(d.get(x, -1)) return ans
682.棒球比賽
注:好久前寫的,後面再吧棧的寫出來
ops= ["35","-32","C","39","+","-48","C","5","88","-52","+","C","D","D","100","C","+","-74","53","59"]
L=[]
sum=[]
lenth=len(ops)
for i in range(0,lenth):
if i==0:
sum.append(int(ops[i]))
else:
if ops[i]=='C': sum.insert(0,0) sum.insert(1,0) sum.pop() elif ops[i]=='D': sum.append(sum[i-1]*2) elif ops[i]=='+': sum.append(sum[i-1]+sum[i-2]) else : sum.append(int(ops[i]))
score=0
for j in sum:
score=score+j
print(score)
232.用棧實現佇列
方法1:網上的,用兩個list來實現
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.stact=[]
self.queue=[]
self.len=0
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.stact.append(x)
self.len=self.len+1
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
while len(self.stact)!=0:
self.queue.append(self.stact.pop())
x = self.queue.pop()
while len(self.queue)!= 0:
self.stact.append(self.queue.pop())
self.len -=1
return x
def peek(self):
"""
Get the front element.
:rtype: int
"""
while len(self.stact)!=0:
self.queue.append(self.stact.pop())
x = self.queue.pop()
self.queue.append(x)
while len(self.queue)!= 0:
self.stact.append(self.queue.pop())
return x
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if self.len==0:
return False
方法2:用一個list來實現,比較簡單
class MyQueue:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.queue.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if len(self.queue)>0:
print( self.queue.pop(0))
def peek(self):
"""
Get the front element.
:rtype: int
"""
if len(self.queue)>0:
print( self.queue[0])
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if len(self.queue)>0:
return False
else:
return True
def shuchu(self):
for i in self.queue:
print(i)
235,用佇列來實現棧
注:與上面異曲同工
class MyStack:
def __init__(self):
"""
Initialize your data structure here.
"""
self.queue = []
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.queue.append(x)
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if len(self.queue)>0:
return self.queue.pop()
#len(self.queue)-=1
def top(self):
"""
Get the front element.
:rtype: int
"""
if len(self.queue)>0:
return self.queue[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
if len(self.queue)>0:
return False
else:
return True
155,最小棧
注:可以使用深複製在裡面找出來最小值,但會超時,很慢很慢
方法1:用min 函式,較慢,因為每次都執行
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.queue = []
self.min=None
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.queue.append(x)
self.min=min(self.queue)
def pop(self):
"""
:rtype: void
"""
if len(self.queue)>0:
self.queue.pop()
self.min=min(self.queue)
return self.queue
def top(self):
"""
:rtype: int
"""
if len(self.queue)>0:
return self.queue[-1]
def getMin(self):
"""
:rtype: int
"""
return self.min
方法2:判斷,比較快
class MinStack(object):
def init(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = None
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.stack.append(x)
if self.min == None or self.min > x:
self.min = x
def pop(self):
"""
:rtype: void
"""
popItem = self.stack.pop()
if len(self.stack) == 0:
self.min = None
return popItem
if popItem == self.min:
self.min = self.stack[0]
for i in self.stack:
if i < self.min:
self.min = i
return popItem
def top(self):
"""
:rtype: int
"""
return self.stack[-1]
def getMin(self):
"""
:rtype: int
"""
return self.min
844.比較含退格的字串
注:注意遇到‘#’時,字串長度為0時的處理,以及兩個“#”,字串長度為0時的處理。PS,這是老子自己寫出來執行最快的程式碼了,程式碼也簡潔,寫了半個小時吧,有一丟丟自豪。還學會了在類裡呼叫函式。一個類裡不能函式呼叫函式。
class Solution:
def backspaceCompare(self, S, T):
"""
:type S: str
:type T: str
:rtype: bool
"""
S1=back(S)
T1=back(T)
if S1==T1:
return True
else:
return False
def back(L):
K=[]
for i in L:
if i=='#' and len(K)!=0:
K.pop()
elif i=='#' and len(K)==0:
pass
else:
K.append(i)
return K
20,有效的括號
注:好久前寫的了,也是在學棧之前寫的,後面把棧的寫出來。
class Solution:
def isValid(self, s):
a=list(s)
b=[] #存放左括號的棧 qc:list當做棧
c={'(':')','[':']','{':'}'} #字典儲存 qc;key:value 鍵:值
for i in a:
if i=='':
return True
elif i in c: #如果是字典中的鍵,即左括號,放進棧
b.append(i)
else:
if len(b)==0: #先判斷是否有左括號存在
return False
else:
#字典得到該鍵的值==棧頂值對應的右括號
if c.get(b[-1])!=i:
return False
else:
del b[-1] #刪除棧頂元素
if len(b)!=0: #若還存在左括號,此時已沒有右括號,出錯
return False
return True
PS.寫這麼一些題還是有用的,至少遇到一些題知道其實是採用了棧的思想,以前都是瞎寫。程式設計還是要有思維。