232. 用栈实现队列,225. 用队列实现栈,20. 有效的括号,1047. 删除字符串中的所有相邻重复项
232. 用栈实现队列
请你仅使用两个栈实现先入先出队列。队列应当支持一般队列支持的所有操作(push、pop、peek、empty):
实现 MyQueue 类:
- void push(int x) 将元素 x 推到队列的末尾
- int pop() 从队列的开头移除并返回元素
- int peek() 返回队列开头的元素
- boolean empty() 如果队列为空,返回 true ;否则,返回 false
说明:
你 只能 使用标准的栈操作 —— 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
示例 1:
输入:
[“MyQueue”, “push”, “push”, “peek”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 1, 1, false]
解释:
MyQueue myQueue = new MyQueue();
myQueue.push(1); // queue is: [1]
myQueue.push(2); // queue is: [1, 2] (leftmost is front of the queue)
myQueue.peek(); // return 1
myQueue.pop(); // return 1, queue is [2]
myQueue.empty(); // return false
class MyQueue:
def __init__(self):
self.s1 = []
self.s2 = []
def push(self, x: int) -> None:
self.s1.append(x)
def pop(self) -> int:
while self.s1:
self.s2.append(self.s1.pop())
res = self.s2.pop()
while self.s2:
self.s1.append(self.s2.pop())
return res
def peek(self) -> int:
while self.s1:
self.s2.append(self.s1.pop())
res = self.s2.pop()
self.push(res)
while self.s2:
self.s1.append(self.s2.pop())
return res
def empty(self) -> bool:
return not self.s1
# 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()
优化:
- peak方法用pop获取return值,并push入栈1
- 栈1和栈2分别处理输入和输出,用于处理push和pop
class MyQueue:
def __init__(self):
self.s1 = []
self.s2 = []
def push(self, x: int) -> None:
self.s1.append(x)
def pop(self) -> int:
if self.s2:
return self.s2.pop()
else:
while self.s1:
self.s2.append(self.s1.pop())
return self.s2.pop()
def peek(self) -> int:
res = self.pop()
self.s2.append(res)
return res
def empty(self) -> bool:
return not (self.s1 or self.s2)
# 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. 用队列实现栈
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
- void push(int x) 将元素 x 压入栈顶。
- int pop() 移除并返回栈顶元素。
- int top() 返回栈顶元素。
- boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
示例:
输入:
[“MyStack”, “push”, “push”, “top”, “pop”, “empty”]
[[], [1], [2], [], [], []]
输出:
[null, null, null, 2, 2, false]
解释:
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // 返回 2
myStack.pop(); // 返回 2
myStack.empty(); // 返回 False
队列实现栈更容易,单队列就可实现。
class MyStack:
def __init__(self):
self.s = []
def push(self, x: int) -> None:
self.s.append(x)
def pop(self) -> int:
return self.s.pop()
def top(self) -> int:
if self.s:
return self.s[-1]
else:
return None
def empty(self) -> bool:
return not(self.s)
# 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. 有效的括号
给定一个只包括 ‘(’,‘)’,‘{’,‘}’,‘[’,‘]’ 的字符串 s ,判断字符串是否有效。有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
- 每个右括号都有一个对应的相同类型的左括号。
示例 1:
输入:s = “()”
输出:true
示例 2:
输入:s = “()[]{}”
输出:true
示例 3:
输入:s = “(]”
输出:false
示例 4:
输入:s = “([])”
输出:true
栈的简单应用
class Solution:
def isValid(self, s: str) -> bool:
res = []
for i in s:
if not res:
res.append(i)
elif i in ('(','{','['):
res.append(i)
elif i == ')' and res:
if res.pop() == '(':
continue
else:
return False
elif i == '}' and res:
if res.pop() == '{':
continue
else:
return False
elif i == ']' and res:
if res.pop() == '[':
continue
else:
return False
else:
return False
return True if not res else False
1047. 删除字符串中的所有相邻重复项
给出由小写字母组成的字符串 s,重复项删除操作会选择两个相邻且相同的字母,并删除它们。在 s 上反复执行重复项删除操作,直到无法继续删除。在完成所有重复项删除操作后返回最终的字符串。答案保证唯一。
示例:
输入:“abbaca”
输出:“ca”
解释:
例如,在 “abbaca” 中,我们可以删除 “bb” 由于两字母相邻且相同,这是此时唯一可以执行删除操作的重复项。之后我们得到字符串 “aaca”,其中又只有 “aa” 可以执行重复项删除操作,所以最后的字符串为 “ca”。
使用简单栈结构可以解决。
class Solution:
def removeDuplicates(self, s: str) -> str:
res = list()
for i in s:
if not res:
res.append(i)
elif res[-1]==i:
res.pop()
else:
res.append(i)
return ''.join(res)
上述代码可以进一步简化
class Solution:
def removeDuplicates(self, s: str) -> str:
res = []
tmp = True
for i in s:
if res and res[-1]==i:
res.pop()
else:
res.append(i)
return ''.join(res)