232.用栈实现队列
用双栈模拟
class MyQueue {
public:
stack<int> stk, tmp;
/** Initialize your data structure here. */
MyQueue() {
}
void move(stack<int>& stk1, stack<int>& stk2)
{
while (stk1.size())
{
stk2.push(stk1.top());
stk1.pop();
}
}
/** Push element x to the back of queue. */
void push(int x) {
stk.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
move(stk, tmp);
int res = tmp.top();
tmp.pop();
move(tmp, stk);
return res;
}
/** Get the front element. */
int peek() {
move(stk, tmp);
int res = tmp.top();
move(tmp, stk);
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return stk.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
225.用队列实现栈
用两个队列模拟栈
class MyStack {
public:
/** Initialize your data structure here. */
queue<int> q, w;
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
q.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
while (q.size() > 1) w.push(q.front()), q.pop();
int t = q.front();
q.pop();
while (w.size()) q.push(w.front()), w.pop();
return t;
}
/** Get the top element. */
int top() {
while (q.size() > 1) w.push(q.front()), q.pop();
int t = q.front();
q.pop();
while (w.size()) q.push(w.front()), w.pop();
q.push(t);
return t;
}
/** Returns whether the stack is empty. */
bool empty() {
return q.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
用一个队列模拟栈
20.有效的括号
哈希表 + 栈解决括号匹配问题
class Solution {
public:
bool isValid(string s) {
unordered_map<char, char> hs
{
{')', '('},
{'}', '{'},
{']', '['}
};
stack<char> stk;
for (auto &c: s)
{
if (c == '(' || c == '{' || c == '[')
stk.push(c);
else if (stk.empty() || stk.top() != hs[c])
return false;
else stk.pop();
}
return stk.empty();
}
};
1047. 删除字符串中的所有相邻重复项
使用栈来去除相邻的重复项
- 遍历列表,并将前一个元素放到栈顶,将当前元素与栈顶比较,再操作栈顶即可
class Solution {
public:
string removeDuplicates(string s) {
string stk;
for (auto c: s)
{
if (!stk.empty() && stk.back() == c)
stk.pop_back();
else stk.push_back(c);
}
return stk;
}
};
577

被折叠的 条评论
为什么被折叠?



