代码随想录 打卡第十天
232 用栈实现队列class MyQueue { public: stackint stIn; stackint 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() { if(stIn.empty() stOut.empty()){ return true; }else{ return false; } } }; /** * 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 { public: queueint q; MyStack() { } void push(int x) { q.push(x); } int pop() { for(int i 1;i q.size();i){ q.push(q.front()); q.pop(); } int result q.front(); q.pop(); return result; } int top() { int result q.back(); return result; } bool empty() { if(q.empty()){ return true; }else{ return false; } } }; /** * 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: stackchar stack; bool isValid(string s) { for(int i 0; i s.size();i){ if(s[i] ( || s[i] [ || s[i] {){ stack.push(s[i]); } if(s[i] )){ if(!stack.empty() stack.top() (){ stack.pop(); }else{ return false; } } if(s[i] ]){ if(!stack.empty() stack.top() [){ stack.pop(); }else{ return false; } } if(s[i] }){ if(!stack.empty() stack.top() {){ stack.pop(); }else{ return false; } } } if(stack.empty()){ return true; }else{ return false; } } };class Solution { public: bool isValid(string s) { if (s.size() % 2 ! 0) return false; // 如果s的⻓度为奇数⼀定不符合要求 stackchar 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(); // st.top() 与 s[i]相等栈弹出元素 } return st.empty(); } };1047 删除字符串中的所有相邻重复项class Solution { public: stackchar q; string removeDuplicates(string s) { for(int i 0;i s.size();i){ if(!q.empty()){ if(s[i] q.top()){ q.pop(); }else{ q.push(s[i]); } }else{ q.push(s[i]); } } string result; result.resize(q.size()); for(int i q.size() - 1;i 0;i--){ result[i] q.top(); q.pop(); } return result; } };