232.用栈实现队列
leetcode题目链接
使用两个栈模拟队列功能
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if (stOut.empty()) {
while (!stIn.empty()) {
int x = stIn.top();
stIn.pop();
stOut.push(x);
}
}
int x = stOut.top();
stOut.pop();
return x;
}
int peek() {
int x = this->pop();
stOut.push(x);
return x;
}
bool empty() {
return stIn.empty() && stOut.empty();
}
};
225. 用队列实现栈
leetcode题目链接
并不能完全照搬上题思路,在这里仅需要一个队列即可。
class MyStack {
public:
queue<int> q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size();
for (int i = 1; i < size; ++i) {
int x = q.front();
q.pop();
q.push(x);
}
int x = q.front();
q.pop();
return x;
}
int top() {
return q.back();
}
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) {
if (s.size() % 2 != 0)
return false;
stack<char> st;
for (char c : s) {
if (c == '(')
st.push(')');
else if (c == '{')
st.push('}');
else if (c == '[')
st.push(']');
else {
if (st.empty())
return false;
if (st.top() != c)
return false;
else
st.pop();
}
}
if (st.empty())
return true;
else
return false;
}
};
1047. 删除字符串中的所有相邻重复项
leetcode题目链接
思路与上题一样,都是相同或相对应元素消除。在这里可以不需要使用额外的栈,直接使用string模拟栈的行为,并且设计好首尾,免去翻转。
class Solution {
public:
string removeDuplicates(string s) {
string result;
for (char c : s) {
if (result.empty() || result.back() != c)
result.push_back(c);
else
result.pop_back();
}
return result;
}
};