Day10
这两天比较忙,好在栈相对简单
232. Implement Queue using Stacks
class MyQueue {
public:
stack<int> in;
stack<int> out;
MyQueue() {
}
void push(int x) {
in.push(x);
}
int pop() {
if(!out.empty()){
int val = out.top();
out.pop();
return val;
}
while(!in.empty()){
out.push(in.top());
in.pop();
}
int val = out.top();
out.pop();
return val;
}
int peek() {
if(!out.empty()){
return out.top();
}
while(!in.empty()){
out.push(in.top());
in.pop();
}
return out.top();
}
bool empty() {
return in.empty() && out.empty();
}
};
225. Implement Stack using Queues
class MyStack {
public:
queue<int> q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size();
for(int i=0; i<size-1; ++i) {
q.push(q.front());
q.pop();
}
int val = q.front();
q.pop();
return val;
}
int top() {
return q.back();
}
bool empty() {
return q.size() == 0;
}
};
20. Valid Parentheses
class Solution {
public:
bool isValid(string str) {
stack<char> s;
for(int i=0; i<str.length(); ++i) {
if(str[i] == '(' || str[i] == '[' || str[i] == '{') {
s.push(str[i]);
}
else {
if(!s.empty()) {
if(str[i] == ')' && s.top() != '(')
return false;
else if(str[i] == ']' && s.top() != '[')
return false;
else if(str[i] == '}' && s.top() != '{')
return false;
else {
s.pop();
}
}
else {
return false;
}
}
}
return s.empty();
}
};
1047. Remove All Adjacent Duplicates In String
class Solution {
public:
string removeDuplicates(string s) {
stack<char> st;
for(auto c : s)
{
if(st.empty() || st.top() != c)
st.push(c);
else if(st.top() == c)
st.pop();
}
string ans = "";
while(!st.empty())
{
ans = st.top() + ans;
st.pop();
}
return ans;
}
};