文章链接:
class MyQueue {
private:
std::stack<int> s1, s2;
public:
MyQueue() {}
/**
* 添加元素到队尾
*/
void push(int x) { s1.push(x); }
/**
* 删除队头的元素并返回
*/
int pop() {
// 先调用 peek 保证 s2 非空
peek();
int top = s2.top();
s2.pop();
return top;
}
/**
* 返回队头元素
*/
int peek() {
if (s2.empty()) {
// 把 s1 元素压入 s2
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
/**
* 判断队列是否为空
*/
bool empty() { return s1.empty() && s2.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 {
queue<int>q;
int top_elem = 0;
public:
MyStack() {
}
void push(int x) {
q.push(x);
top_elem = x;
}
int pop() {
int size = q.size();
while(size >2){
q.push(q.front());
q.pop();
size--;
}
top_elem = q.front();
q.push(q.front());
q.pop();
int tmp = q.front();
q.pop();
return tmp;
}
int top() {
return top_elem;
}
bool empty() {
return q.empty();
}
};
20
class Solution {
public:
bool isValid(string s) {
stack<char>left;
for(char c:s){
if(c == '(' || c== '{' || c == '[')
left.push(c);
else
if(!left.empty() && leftOf(c)== left.top())
left.pop();
else
return false;
}
return left.empty();
}
private:
char leftOf(char c){
if(c == '}') return '{';
if(c == ')') return '(';
return '[';
}
};
1047
class Solution {
public:
string removeDuplicates(string s) {
string temp = "";
int i = 0;
while(i <s.length()){
if(temp.empty() || s[i]!=temp.back()){
temp.push_back(s[i]);
}else{
temp.pop_back();
}
i++;
}
return temp;
}
};