解法:注意peak()方法,复用了pop()方法,这样就避免了再写一次pop()方法里面的一大堆判空的逻辑。
class MyQueue ( object ) :
def __init__ ( self) :
self. stack_in = [ ]
self. stack_out = [ ]
def push ( self, x) :
"""
:type x: int
:rtype: None
"""
self. stack_in. append( x)
def pop ( self) :
"""
:rtype: int
"""
if self. empty( ) :
return None
if self. stack_out:
return self. stack_out. pop( )
else :
for i in range ( len ( self. stack_in) ) :
self. stack_out. append( self. stack_in. pop( ) )
return self. stack_out. pop( )
def peek ( self) :
"""
:rtype: int
"""
ans = self. pop( )
self. stack_out. append( ans)
return ans
def empty ( self) :
"""
:rtype: bool
"""
return not ( self. stack_out or self. stack_in)
解法:遍历字符串,若当前元素与栈内最后一个相同,则栈内最后一个元素出栈,否则当前元素入栈。
class Solution ( object ) :
def removeDuplicates ( self, s) :
"""
:type s: str
:rtype: str
"""
stack = [ 0 ]
for i in s:
if stack[ - 1 ] == i:
stack. pop( )
else :
stack. append( i)
return '' . join( stack[ 1 : ] )
解法:匹配失败的三种情况:1.左括号多余;2.右括号多余;3.左右都不多余,只是类型不匹配。那么对应到代码实现便是:1.遍历完字符串最终栈不为空,对应左括号多余;2.遍历的过程中栈空了,说明右括号多余了;3.遍历的过程中,栈里没有要匹配的元素,说明类型不匹配。
class Solution ( object ) :
def isValid ( self, s) :
"""
:type s: str
:rtype: bool
"""
if len ( s) % 2 != 0 :
return False
stack = [ ]
for i in s:
if i == '[' :
stack. append( ']' )
elif i == '(' :
stack. append( ')' )
elif i == '{' :
stack. append( '}' )
elif not stack or stack[ - 1 ] != i:
return False
else :
stack. pop( )
return not stack
解法: Python普通的Queue或SimpleQueue没有类似于peak的功能也无法用索引访问,在实现top的时候较为困难。 用list可以,但是在使用pop(0)的时候时间复杂度为O(n) 因此这里使用双向队列,我们保证只执行popleft()和append(),因为deque可以用索引访问,可以实现和peak相似的功能。
from collections import deque
class MyStack ( object ) :
def __init__ ( self) :
self. queue_in = deque( )
self. queue_out = deque( )
def push ( self, x) :
"""
:type x: int
:rtype: None
"""
self. queue_in. append( x)
def pop ( self) :
"""
:rtype: int
"""
if self. empty( ) :
return None
for i in range ( len ( self. queue_in) - 1 ) :
self. queue_out. append( self. queue_in. popleft( ) )
self. queue_in, self. queue_out = self. queue_out, self. queue_in
return self. queue_out. popleft( )
def top ( self) :
"""
:rtype: int
"""
if self. empty( ) :
return None
return self. queue_in[ - 1 ]
def empty ( self) :
"""
:rtype: bool
"""
return len ( self. queue_in) == 0