232.用栈实现队列
-
借助另一个栈
-
第一个栈为入栈,第二个栈为出栈
-
假设元素入栈顺序为1->2->3; 为了实现跟队列一样先出先进
-
使用另外一个栈作为当第一个栈出栈的时候3->2->1保存到第二个栈
-
这样跟第二栈出栈顺序跟队列就一样了
-
-
注意我们必须要把第一个栈的元素全部存入到第二个栈,不然第二个栈出栈的时候元素会乱
class MyQueue(object):
def __init__(self):
"""
stack_in 负责 push
stack_out 负责 pop
"""
self.stack_in = []
self.stack_out = []
def push(self, x):
"""
:type x: int
:rtype: None
有新元素进来push到stack_in
"""
self.stack_in.append(x)
def pop(self):
"""
:rtype: int
"""
# 检查队列是否为空
if self.empty():
return None
#检查stack_out是否为空
if self.stack_out:
# 不为空,返回顶部元素
return self.stack_out.pop()
#为空
else:
#把stack_in 里面的元素添加进去
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
peek 方法用于查看队列前端的元素,而不移除它。
"""
ans = self.pop()
self.stack_out.append(ans)
return ans
def empty(self):
"""
:rtype: bool
只要in或者out有元素,说明队列不为空
"""
return not(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()
225. 用队列实现栈
-
使用一个队列模拟栈
2. 栈: 1->2->->3(入栈顺序)
3. 队列: 把元素1取出来后,再次加入队列中
1. 把元素2取出来后,再次加入队列里
2. 这样就能弹出元素3了
3. 弹出size-1的元素弹出来就好(最后一个元素)
class MyStack(object):
def __init__(self):
self.que = deque()
def push(self, x):
"""
:type x: int
:rtype: None
添加元素到队列
"""
self.que.append(x)
def pop(self):
"""
:rtype: int
如果栈为空返回None
否则把队列的前 size-1个元素全部弹出去
"""
if self.empty():
return None
for i in range(len(self.que)-1):
# 把弹出去的值从加入到队列直到队列第一个元素是栈第一个元素
self.que.append(self.que.popleft())
return self.que.popleft()
def top(self):
"""
:rtype: int
"""
if self.empty():
return None
# return 队列back,因为队列的front是出口,back是入口,根据先进先出原则,栈里面第一个元素就是队列最后进入的元素
return self.que[-1]
def empty(self):
"""
:rtype: bool
"""
return not self.que
# 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()
20. 有效的括号
- 要明确三点: 括号数量要匹配,括号类型要匹配,括号顺序要匹配
-
遇到左括号,把对应的右括号加入栈
-
匹配的时候,直接弹出来和栈里面这个元素比较就行
-
所谓作比较就是往后面遍历存储括号的字符串的时候,(第一种情况)
-
如果后面元素跟栈存储的括号不一样就说明不符合规则 如果字符串遍历完了,但是栈还有滞留的元素,说明不匹配
-
在字符串跟栈元素进行比较的时候,如果栈顶部元素跟当前字符串不匹配,不符合要求(第二种情况)
-
字符串没遍历完,但是栈空了,说明括号多了,不符合要求(第三种情况)
-
-
class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
three situation if would be false:
1. the top of stack element is not same as current element
2. before we iterate the whole stirng, the stack is empty
3. after iterate the string, stack still have element
those three situation above will return False
"""
# create a stack
stack = []
# reduce calculate speed, if string is odd, means it can't be true
if len(s) % 2 != 0:
return False
# iterate the string
for item in s:
# all the left parentheses, we will add right parentheses into our stack
if item == '(':
stack.append(")")
elif item == '[':
stack.append("]")
elif item == '{':
stack.append('}')
# now compare parenthese with our stack, to see if they were match our not
# check if our stack is empty or not; or check stack top element match to our current element our not
elif not stack or stack[-1] != item:
# it match situation 1 and 2
return False
else:
# means the parenthese match pop the element
stack.pop()
# return if stack were empty, if stack is not empty means there are extra parenthese return false
return True if not stack else False
1047. 删除字符串中的所有相邻重复项
- 使用栈取实现删除字符串中所有相邻重复项
- 我们创建一个栈,每遍历字符串里面的一个单词就存入到栈中
- 如果栈是空的,或者栈顶部的元素和当前遍历的元素不一样
- 我们把该元素push到栈里
- 否则说明当前元素和栈顶部元素相等
- 把栈顶的元素pop出去
- 循环结束后我们就能得到新的字符串
class Solution(object):
def removeDuplicates(self, s):
"""
:type s: str
:rtype: str
"""
# create a stack
result = list()
# iterate the list
for item in s:
# if the string is empty or current element is different than the element top stack
if not result or result[-1] != item:
# add element into stack
result.append(item)
# the element are equal
else:
# let them pop out the stack
result.pop()
# convert to string return answer
return "".join(result)