代码随想录算法训练营第11天|232,225,20.1047

75 阅读1分钟

232 用栈实现队列

第一思路

定义两个stack分别正序和顺序存放

class MyQueue {
private:
    stack<int> stack1; // 
    stack<int> stack2;
public:
    MyQueue() {

    }

    
    void push(int x) {

        stack1.push(x);
        stack<int> tmp = stack1;
        while (!tmp.empty()){
            stack2.push(tmp.top());
            tmp.pop();
        }

    }
    //清空stack
    void clearStack(stack<int> & sta) {
        while (!sta.empty()) {
            sta.pop();
        }
    }
    
    int pop() {
        int res = stack2.top();
        stack2.pop();
        stack<int> tmp = stack2;
        clearStack(stack1);
        while (!tmp.empty()) {
            stack1.push(tmp.top());
            tmp.pop();
        }
        return res;


    }
    
    int peek() {
        return stack2.top();

    }
    
    bool empty() {
        return stack1.empty() ? true : 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();
 */

结果不知为何有的示例能过,有的过不了

总结

实际上不需要中间变量去同步两个栈中的元素,关键点在于,当stackout为空的时候,把stackin中的元素全部添加进去即可 然后注意下peek中函数复用的思想.

225

总结: 注意点在于 size可以使用,一开始忽略了,然后,back也是可以使用的

20

总结: 注意三种情况和左括号压栈

1047

思路

遍历字符串,从后往前压栈,如果新元素和栈顶元素重复,则弹出这个元素,并且暂存(暂存是为了处理3个以上相连元素)

class Solution {
public:
    string removeDuplicates(string s) {
        // 思路
        // 遍历字符串,从后往前压栈,如果新元素和栈顶元素重复,则弹出这个元素,并且暂存(暂存是为了处理3个以上相连元素)
        stack<char> st;
        char tmp = ' ';
        for (int i = s.size() - 1; i >= 0; i--) {
            if (st.empty()) {
                st.push(s[i]);
            }
            else if (s[i] != st.top() && s[i] != tmp) {
                st.push(s[i]);
                
            }
            else if (s[i] == st.top()) {
                tmp = s[i];
                st.pop();
            }
        }
        string res;
        while ( !st.empty()) {
            res = res + st.top();
            st.pop();
        }
        return res;

    }
};

结果有的测试用例不通过

总结

这里想多了,此题是两两相连,然后注意用string 模拟栈的操作即可。