典型应用场景
进制转换
def convert(n,a):
res=[]
while n:
res.append(n%a)
n=n//a
while res:
print (res.pop())
括号匹配
class Solution:
"""
@param s: A string
@return: whether the string is a valid parentheses
"""
def isValidParentheses(self, s):
# write your code here
s=list(s)
stack=[]
match={"(":")","[":"]","{":"}"}
for letter in s:
if letter in match:
stack.append(letter)
elif letter in match.values():
if not stack:
return False
left=stack.pop()
if match[left]!=letter:
return False
return len(stack)==0
栈混洗
判断出栈序列是否合法
def legal(n,lst):
stack1=[]
for i in range(1,n+1):
stack1.append(i)
while lst and stack1 and lst[0]==stack1[-1]:
lst.pop(0)
stack1.pop()
return stack1==[] and lst==[]
print (legal(5,[3,1,2,4,5]))
print (legal(5,[3,2,5,4,1]))
中缀表达式求值
trapping rain water
对于每一个bar来说,能装水的容量取决于左右两侧bar的最大值。扫描两次,一次从左向右,记录对于每一个bar来说其左侧的bar的最大高度left[i],一次从右向左,记录每一个bar右侧bar的最大高度right[i]。第三次扫描,则对于每一个bar,计算(1)左侧最大height和当前bar的height的差值(left[i] - heights[i]) (2)右侧最大height和当前bar的height的差值(right[i] - heights[i]),取(1),(2)中结果小的那个作为当前bar的蓄水量。最终求和得到总蓄水量。
#栈的方法没看懂
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
left=[0]*len(height)
right=[0]*len(height)
# Keep track of the max height on the left of height[i]
leftM=0
for i in range(1,len(height)):
leftM=max(height[i-1],leftM)
left[i]=leftM
# Keep track of the max height on the right of height[i]
rightM=0
for i in range(len(height)-2,-1,-1):
rightM=max(height[i+1],rightM)
right[i]=rightM
# Keep track of the max height on the right of height[i]
res=0
for i in range(len(height)):
if min(left[i]-height[i],right[i]-height[i])>0:
res+=min(left[i],right[i])-height[i]
return res