letcode 分类练习 栈和队列 232.用栈实现队列 225. 用队列实现栈 20. 有效的括号 1047. 删除字符串中的所有相邻重复项
232.用栈实现队列
两个栈,一个栈负责输入,一个栈负责输出,如果输出栈空了就从输入栈里面导入
class MyQueue {
public:
stack<int> s1;
stack<int> s2;
MyQueue() {
}
void push(int x) {
s1.push(x);
}
int pop() {
if(s2.empty()){
while(!s1.empty()){
int val = s1.top();
s1.pop();
s2.push(val);
}
}
int x = s2.top();
s2.pop();
return x;
}
int peek() {
if(s2.empty()){
while(!s1.empty()){
int val = s1.top();
s1.pop();
s2.push(val);
}
}
return s2.top();
}
bool empty() {
return s1.empty() && s2.empty();
}
};
225. 用队列实现栈
这里两个队列的用法跟上题目不同,因为队列是先进先出,就算你导入新的队列顺序也是一样的,所以我们把另个队列纯当备份使用。要进行模拟栈输出的时候我们就从头开始倒到备份队列,到最后一个元素单独处理,然后再把备份队列的元素再倒回来。
class MyQueue {
public:
stack<int> s1;
stack<int> s2;
MyQueue() {
}
void push(int x) {
s1.push(x);
}
int pop() {
if(s2.empty()){
while(!s1.empty()){
int val = s1.top();
s1.pop();
s2.push(val);
}
}
int x = s2.top();
s2.pop();
return x;
}
int peek() {
if(s2.empty()){
while(!s1.empty()){
int val = s1.top();
s1.pop();
s2.push(val);
}
}
return s2.top();
}
bool empty() {
return s1.empty() && s2.empty();
}
};
20. 有效的括号
用map绑定好这些括号,注意当前元素是如‘{’的时候,必须要求当前栈顶是’}'才能满足要求
class Solution {
public:
bool isValid(string s) {
int n = s.size();
if (n % 2 == 1) {
return false;
}
unordered_map<char, char> pairs = {
{')', '('},
{']', '['},
{'}', '{'}
};
stack<char> stk;
for (char ch: s) {
if (pairs.count(ch)) {
if (stk.empty() || stk.top() != pairs[ch]) {
return false;
}
stk.pop();
}
else {
stk.push(ch);
}
}
return stk.empty();
}
};
1047. 删除字符串中的所有相邻重复项
解法1
用栈模拟消消乐
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(auto c : s){
if(!st.empty() && st.top() == c)st.pop();
else st.push(c);
}
string result;
while(!st.empty()){
result += st.top();
st.pop();
}
// 得倒叙还原为字符串
reverse(result.begin(), result.end());
return result;
}
};
解法2
字符串自带的类栈操作,push_back()、pop_back()、back()和empty()
class Solution {
public:
string removeDuplicates(string s) {
string stk;
for (char ch : s) {
if (!stk.empty() && stk.back() == ch) {
stk.pop_back();
} else {
stk.push_back(ch);
}
}
return stk;
}
};