Day 10

232. 用栈实现队列

class MyQueue
{
private:
    stack<int> in_stack, out_stack;

    void in2out()
    {
        while (!in_stack.empty())
        {
            out_stack.push(in_stack.top());
            in_stack.pop();
        }
    }
public:
    MyQueue()
    {
    }

    void push(int x)
    {
        in_stack.push(x);
    }

    int pop()
    {
        if (out_stack.empty())
        {
            in2out();
        }

        auto temp{ out_stack.top() };
        out_stack.pop();

        return temp;
    }

    int peek()
    {
        if (out_stack.empty())
        {
            in2out();
        }

        return out_stack.top();
    }

    bool empty()
    {
        return in_stack.empty() && out_stack.empty();
    }
};

225. 用队列实现栈

class MyStack
{
private:
    queue<int> stack;
public:
    MyStack()
    {
    }

    void push(int x)
    {
        stack.push(x);

        if (stack.size() > 1)
        {
            for (int i = 0; i < stack.size() - 1; i++)
            {
                auto temp{ stack.front() };
                stack.pop();
                stack.push(temp);
            }
        }
    }

    int pop()
    {
        auto temp{ stack.front() };
        stack.pop();
        return temp;
    }

    int top()
    {
        return stack.front();
    }

    bool empty()
    {
        return stack.empty();
    }
};

20. 有效的括号

class Solution
{
public:
    bool isValid(string s)
    {
        stack<char> stk;

        for (auto& ch : s)
        {
            if (ch == '(' || ch == '{' || ch == '[')
            {
                stk.push(ch);
            }
            else if (stk.empty())
            {
                return false;
            }
            else
            {
                if (stk.top() == '(' && ch == ')' ||
                    stk.top() == '{' && ch == '}' ||
                    stk.top() == '[' && ch == ']')
                {
                    stk.pop();
                }
                else
                {
                    return false;
                }
            }
        }

        return stk.empty();
    }
};

1047. 删除字符串中的所有相邻重复项 

class Solution
{
public:
    string removeDuplicates(string s)
    {
        string ans;

        for (auto& ch : s)
        {
            if (ans.empty())
            {
                ans.push_back(ch);
            }
            else
            {
                if (ans.back() == ch)
                {
                    ans.pop_back();
                }
                else
                {
                    ans.push_back(ch);
                }
            }
        }

        return ans;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值