题目链接:232. 用栈实现队列 - 力扣(LeetCode)
思路:用一个堆栈当作入堆栈,另一个堆栈作为出堆栈。当push时,将元素压入入队栈,当pop时,分两种情况。第一种情况:如果出堆栈没有元素,则将所有的入队栈元素压入出堆栈,然后将最后一个元素出栈;第二种情况:如果出堆栈有元素,则直接进行pop
class MyQueue:
def __init__(self):
self.stack_in = [] # 用来存放入栈的元素
self.stack_out = [] # 用来存放出栈的元素
def push(self, x: int) -> None:
self.stack_in.append(x)
def pop(self) -> 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) -> int:
ans = self.pop()
self.stack_out.append(ans)
return ans
def empty(self) -> bool:
if len(self.stack_in) != 0 or len(self.stack_out) != 0:
return False
else:
return True
# 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. 用队列实现栈 - 力扣(LeetCode)
思路:思路就是,当pop元素时,需要pop的是最后一个元素,队列的操作只有出头元素,所以只要保留最后一个元素,将最后一个前面的元素全部添加到末尾即可,最后将第一个元素pop即可
class MyStack:
def __init__(self):
self.queue = deque()
def push(self, x: int) -> None:
self.queue.append(x)
def pop(self) -> int:
if self.empty():
return None
else:
for i in range(len(self.queue) - 1):
self.queue.append(self.queue.popleft()) #不断地将第一个元素添加到最后一个元素
return self.queue.popleft()
def top(self) -> int:
if self.empty():
return None
else:
return self.queue[-1]
def empty(self) -> bool:
if len(self.queue) == 0:
return True
else:
return False
# 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()
思路:思路很简单,当碰到右括号时,判断堆栈顶上的字符是不是匹配的字符,或者堆栈还有没有字符,以及循环结束后,堆栈中还有没有剩余字符
class Solution:
def isValid(self, s: str) -> bool:
help_stack = []
for x in s:
if x == "(" or x == "[" or x == "{":
help_stack.append(x)
else:
if len(help_stack) == 0:
return False
elif x == ")" and help_stack.pop() != "(":
return False
elif x == "}" and help_stack.pop() != "{":
return False
elif x == "]" and help_stack.pop() != "[":
return False
else:
continue
if len(help_stack) != 0:
return False
return True
题目链接:1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
class Solution:
def removeDuplicates(self, s: str) -> str:
help_stack = []
for x in s:
if len(help_stack) == 0:
help_stack.append(x)
continue
if x == help_stack[-1]:
while x == help_stack[-1]:
help_stack.pop()
if len(help_stack) == 0:
break
else:
help_stack.append(x)
return "".join(help_stack)