232.用栈实现队列
题目链接:https://leetcode.cn/problems/implement-queue-using-stacks/
思路:用两个栈来实现队列元素的进出操作。
class MyQueue {
public:
stack<int> stackin;
stack<int> stackout;
MyQueue() {
}
void push(int x) {
stackin.push(x); //元素x压入队列的同时压入栈顶
}
int pop() { //从队列头移除元素并返回元素
// 只有当stackout为空的时候,再从stackin里导入全部数据
if(stackout.empty()){
while(!stackin.empty()){
stackout.push(stackin.top());
stackin.pop();
}
}
int result = stackout.top();
stackout.pop();
return result;
}
int peek() { //查看栈顶元素
int res = this->pop();
stackout.push(res);
return res;
}
bool empty() {
return stackin.empty() && stackout.empty();
}
};
225. 用队列实现栈
题目链接:”https://leetcode.cn/problems/implement-stack-using-queues/description/
思路:用一个队列加循环操作实现栈的出入。
class MyStack { //关键在于如何弹出元素 用一个队列来模拟弹出和重新添加
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
size--;
while(size>0){ //将队列头部元素除了最后一个元素重新添加到队列尾部
que.push(que.front());
que.pop();
size--;
}
int res = que.front(); //弹出元素为栈的顺序
que.pop();
return res;
}
int top() {
return que.back();
}
bool empty() {
return que.empty();
}
};
20. 有效的括号
题目链接:https://leetcode.cn/problems/valid-parentheses/description/
思路:给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串 s
,判断字符串是否有效。要分清楚括号不匹配的三种情况, 1、左括号多余不匹配 2、括号类型没匹配上 3、右括号多余不匹配。剩下的就好说了。
class Solution { //括号匹配 1、左括号多余不匹配 2、括号类型没匹配上 3、右括号多余不匹配
public:
bool isValid(string s) {
if(s.size() % 2 != 0)
return false; //s长度为奇数直接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
return false;
else
st.pop();
}
if(!st.empty())
return false; //遍历完字符串,栈不为空,返回false;
return st.empty(); //正常匹配的话栈一定是空的
}
};
1047. 删除字符串中的所有相邻重复项
题目链接:https://leetcode.cn/problems/remove-all-adjacent-duplicates-in-string/submissions/546385196/
思路:用栈来实现相邻元素匹配的消除操作
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(char S : s){
if(st.empty() || S != st.top()){
st.push(S);
}else{
st.pop();
}
}
string res = "";
while(!st.empty()){ //将栈中元素放到res字符串中汇总
res += st.top();
st.pop();
}
reverse(res.begin(),res.end());
return res;
}
};