当前位置: 首页> 健康> 知识 > 【LC刷题】DAY09:232 225 20 1047

【LC刷题】DAY09:232 225 20 1047

时间:2025/7/13 4:54:10来源:https://blog.csdn.net/weixin_45338913/article/details/139708844 浏览次数:0次

【LC刷题】DAY09:232 225 20 1047

文章目录

  • 【LC刷题】DAY09:232 225 20 1047
    • 232. 用栈实现队列 [link](https://leetcode.cn/problems/implement-queue-using-stacks/description/)
    • 225. 用队列实现栈[]()
    • 20. 有效的括号
    • 1047. 删除字符串中的所有相邻重复项

232. 用栈实现队列 link

class MyQueue {
private:stack<int> inStack, outStack;void in2out(){while(!inStack.empty()){outStack.push(inStack.top());inStack.pop();}}public:MyQueue() {}void push(int x) {inStack.push(x);}int pop() {if(outStack.empty()){in2out();}int x = outStack.top();outStack.pop();return x;}int peek() {if(outStack.empty()){in2out();}return outStack.top();}bool empty() {return inStack.empty() && outStack.empty();}
};/*** Your MyQueue object will be instantiated and called as such:* MyQueue* obj = new MyQueue();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->peek();* bool param_4 = obj->empty();*/

225. 用队列实现栈

class MyStack {private:queue<int> queue1, queue2;
public:MyStack() {}void push(int x) {queue2.push(x);while(!queue1.empty()){queue2.push(queue1.front());queue1.pop();}swap(queue1, queue2);}int pop() {int r = queue1.front();queue1.pop();return r;}int top() {int r = queue1.front();return r;}bool empty() {return queue1.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) {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. 删除字符串中的所有相邻重复项

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;}
};
关键字:【LC刷题】DAY09:232 225 20 1047

版权声明:

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

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

责任编辑: