代码随想录 代码随想录
232. 用栈实现队列
class MyQueue {
public:
MyQueue() {
stack<int> stackIn;
stack<int> stackOut;
}
void push(int x) { stackIn.push(x); }
int pop() {
if (stackOut.empty()) {
while (!stackIn.empty()) {
stackOut.push(stackIn.top());
stackIn.pop();
}
}
int res = stackOut.top();
stackOut.pop();
return res;
}
int peek() {
int res = this->pop();
stackOut.push(res);
return res;
}
bool empty() { return stackIn.empty() && stackOut.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:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
size--;
while (size--) {
que.push(que.front());
que.pop();
}
int res = que.front();
que.pop();
return res;
}
int top() {
int res = this->pop();
que.push(res);
return res;
}
bool empty() {
return que.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) {
stack<char> st;
for (char c : s) {
switch(c) {
case '(' :
st.push(')');
break;
case '[' :
st.push(']');
break;
case '{' :
st.push('}');
break;
case ')':
case ']':
case '}': {
if (st.empty() || st.top() != c) {
return false;
} else {
st.pop();
}
break;
}
}
}
return st.empty();
}
};
1047. 删除字符串中的所有相邻重复项
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for (auto c : s) {
if (!st.empty() && c == st.top()) {
st.pop();
} else {
st.push(c);
}
}
string res;
while (!st.empty()) {
res = st.top() + res;
st.pop();
}
return res;
/*
以上也可以:
while (!st.empty()) { // 将栈中元素放到result字符串汇总
res += st.top();
st.pop();
}
reverse (res.begin(), res.end()); // 此时字符串需要反转一下
return res;
这样似乎性能更好一些
*/
}
};