算法刷题记录.leetcode 232.用栈实现队列 & 225. 用队列实现栈 & 20. 有效的括号 & 1047. 删除字符串中的所有相邻重复项

63 阅读1分钟

232

  • 栈的定义 stack<int> stIn;
  • 思路简单,用两个栈依次过滤一段数据即可实现队列效果。
class MyQueue {

public:

stack<int> stackIn;

stack<int> stackOut;

\


MyQueue() {

\


}

void push(int x) {

stackIn.push(x);

}

int pop() {

int res = -1;

if(stackOut.empty()){

while(!stackIn.empty()){

stackOut.push(stackIn.top());

stackIn.pop();

}

}

res = stackOut.top();

stackOut.pop();

return res;

}

int peek() {

int res = this->pop();

stackOut.push(res);

return res;

}

bool empty() {

if(stackIn.empty() && stackOut.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:

queue<int> queue;

\


MyStack() {

\


}

void push(int x) {

queue.push(x);

}

int pop() {

int size = queue.size();

while(size != 1){

int a = queue.front();

queue.pop();

queue.push(a);

size--;

}

int a = queue.front();

queue.pop();

return a;

}

int top() {

return queue.back();

}

bool empty() {

return queue.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

  • 不要用if+continue, 用else if进行判断。
class Solution {

public:

bool isValid(string s) {

stack<char> stack;

if (s.size() % 2 != 0) return false;

for(int i = 0; i < s.size(); i++){

if(s[i] == '(' ){

stack.push(')');

}

else if(s[i] == '[' ){

stack.push(']');

}

else if(s[i] == '{' ){

stack.push('}');

}

else if(s[i] == ')' && !stack.empty() && stack.top() == ')'){

stack.pop();

}

else if(s[i] == ']' && !stack.empty() && stack.top() == ']'){

stack.pop();

}

else if(s[i] == '}' && !stack.empty() && stack.top() == '}'){

stack.pop();

}else{

return false;

}

}

if(stack.empty()==true){

return true;

}else{

return false;

}

}

};

1047

  • 删除重复字符想到双指针,可本题要求重复删除重复字符。用栈最简单快捷。 class Solution {

public:

string removeDuplicates(string s) {

stack stack;

for(int i = 0; i < s.size(); i++ ){

if(stack.empty()){

stack.push(s[i]);

}

else if(!stack.empty() && stack.top() != s[i]){

stack.push(s[i]);

}else{

stack.pop();

}

}

string t = "";

while(!stack.empty()){

t += stack.top();

stack.pop();

}

reverse(t.begin(),t.end());

return t;

}

};