232.用栈实现队列
class MyQueue {
private:
stack<int> in_;
stack<int> out_;
public:
MyQueue() {
}
void push(int x) {
in_.push(x);
}
int pop() {
if(out_.empty()){
while(!in_.empty()){
out_.push(in_.top());
in_.pop();
}
}
int val=out_.top();
out_.pop();
return val;
}
int peek() {
int val=pop();
out_.push(val);
return val;
}
bool empty() {
return in_.empty()&&out_.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> q_;
public:
MyStack() {
}
void push(int x) {
q_.push(x);
}
int pop() {
for(int i=0;i<q_.size()-1;i++){
q_.push(q_.front());
q_.pop();
}
int val=q_.front();
q_.pop();
return val;
}
int top() {
int val=pop();
push(val);
return val;
}
bool empty() {
return q_.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) {
stack<char> st;
for(auto c:s){
switch(c){
case '(':
case '[':
case '{':
st.push(c);
break;
case ')':
if(!st.empty()&&st.top()=='('){
st.pop();
break;
}
else
return false;
case ']':
if(!st.empty()&&st.top()=='['){
st.pop();
break;
}
else
return false;
case '}':
if(!st.empty()&&st.top()=='{'){
st.pop();
break;
}
else
return false;
}
}
return st.empty();
}
};
1047. 删除字符串中的所有相邻重复项
class Solution {
public:
string removeDuplicates(string s) {
string res;
for(int i=0;i<s.size();i++){
if(!res.empty()&&s[i]==res.back()){
res.pop_back();
}
else
res.push_back(s[i]);
}
return res;
}
};
string提供push_back和pop_back接口,天然栈。