232.用栈实现队列
要点:用栈实现队列,队列是先进先出,要实现取队列头部的元素,就要把栈中的元素一个个拿出来,直到取出第一个,再把取出的元素一个个放回去,所以很容易就可以想到,需要额外的数据结构来保存取出的元素
方法:
1. 两个数据结构,一个出栈,一个入栈
2. 要实现取队列顶端的元素,push的时候,往入栈里push,pop的时候,先从出栈里弹,如果出栈为空,就按照先进后出的原则,把入栈的元素一个个放进出栈,再从出栈里弹
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()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
if (stOut.empty()) {
while (!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
return result;
}
bool empty() { return stIn.empty() && stOut.empty(); }
};
225.用队列实现栈
要点:重点在出栈pop的操作,把第一个元素之前的元素都推进第二个队列,pop掉之后,再把第二个队列的元素复制给第一个队列
方法:
1. 两个队列,第二个队列用于删除栈顶元素的时候备份除要删除元素外的其他元素
class MyStack {
public:
queue<int> que1;
queue<int> que2;
MyStack() {}
void push(int x) { que1.push(x); }
int pop() {
int size = que1.size() - 1;
while (size--) {
que2.push(que1.front());
que1.pop();
}
int result = que1.front();
que1.pop();
que1 = que2;
while (!que2.empty()) {
que2.pop();
}
return result;
}
int top() { return que1.back(); }
bool empty() { return que1.empty(); }
};
20.有效的括号
要点:括号的特点是左右对称,最先有的左括号,与其匹配的右括号一定在最后,符合栈的先进后出原则,所以用栈
方法:
1. 遍历 碰到左括号就压进栈里
2. 碰到右括号就判断栈顶的括号元素是不是与之匹配
3. 匹配就pop,不匹配就false
4. 遍历完,栈不为空也是false
class Solution {
public:
bool isValid(string s) {
if (s.size() % 2 != 0)
return false;
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(')
st.push(')');
else if (s[i] == '{')
st.push('}');
else if (s[i] == '[')
st.push(']');
else if (st.empty() || st.top() != s[i])
return false;
else
st.pop();
}
return st.empty();
}
};
1047.删除字符串中的所有相邻重复项
要点:要想到能用栈,找到需要消除的重复项的规律
方法:
1. 遍历 栈为空或栈顶元素不等于当前遍历的元素,push,否则pop
2. 拼接result字符串,栈先进后出,所以result还需要反转一次
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for (char ss : s) {
if (st.empty() || st.top() != ss) {
st.push(ss);
} else {
st.pop();
}
}
string result = "";
while (!st.empty()) {
result += st.top();
st.pop();
}
reverse(result.begin(), result.end());
return result;
}
};