当前位置: 首页> 房产> 建材 > 代码随想录第九天| 232.用栈实现队列 225. 用队列实现栈 20. 有效的括号 1047. 删除字符串中的所有相邻重复项

代码随想录第九天| 232.用栈实现队列 225. 用队列实现栈 20. 有效的括号 1047. 删除字符串中的所有相邻重复项

时间:2025/7/11 15:32:14来源:https://blog.csdn.net/m0_73596392/article/details/141953216 浏览次数:0次
class MyQueue {
public:stack<int> in;//输入栈stack<int> out;//输出栈MyQueue() {}void push(int x) {in.push(x);}int pop() {if(!out.empty()){int res=out.top();out.pop();return res;}else{//可能有人会疑惑会不会重复插入实则不会 因为之前插入的在非空情况下都会被弹出while(!in.empty()){out.push(in.top());in.pop();}}int res=out.top();out.pop();return res;}int peek() {if(!out.empty()){int res=out.top();return res;}else{//可能有人会疑惑会不会重复插入实则不会 因为之前插入的在非空情况下都会被弹出while(!in.empty()){out.push(in.top());in.pop();}}int res=out.top();return res;}   bool empty() {if(in.empty()&&out.empty())return true;return false;}
};

栈实现队列

思路:很不错的题 利用输入输出流的原理 使得输入缓冲 到输出的时候 进入输出栈 实现队列

队列实现栈

思路:

用一个队列就可以实现很厉害的思路

class MyStack {
public:queue<int> q;MyStack() {}void push(int x) {q.push(x);}int pop() {int size=q.size();size--;while(size--){int temp=q.front();q.pop();q.push(temp);}int res=q.front();q.pop();return res;}int top() {int size=q.size();size--;while(size--){int temp=q.front();q.pop();q.push(temp);}int res=q.front();int temp=q.front();q.pop();q.push(temp);return res;}bool empty() {if(q.empty())return true;return false;}
};

匹配括号

思路:用栈对匹配

class Solution {
public:bool isValid(string s) {if (s.empty())return true;stack<char> st;for (char c : s) {if (c == '(' || c == '{' || c == '[') {st.push(c);  // 左括号入栈} else {// 右括号处理if (st.empty()) {// 如果栈为空,说明没有匹配的左括号return false;}char now = st.top();st.pop();  // 匹配成功,弹出栈顶元素// 检查匹配的括号if ((now == '(' && c != ')') ||(now == '{' && c != '}') ||(now == '[' && c != ']')) {return false;}}}// 最终栈应该为空,如果不为空说明有未匹配的左括号return st.empty();}
};

重复项删除操作

思路:栈实现

class Solution {
public:string removeDuplicates(string s) {stack<char> st;for(char c:s){if(st.empty())st.push(c);else{char temp=st.top();if(c==temp){st.pop();} else{st.push(c);}}}string res;while(!st.empty()){res+=st.top();st.pop();}reverse(res.begin(),res.end());return res;}
};

关键字:代码随想录第九天| 232.用栈实现队列 225. 用队列实现栈 20. 有效的括号 1047. 删除字符串中的所有相邻重复项

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: