代码随想录算法训练营第十天 | 232.用栈实现队列, 225. 用队列实现栈, 20. 有效的括号 & 1047. 删除字符串中的所有相邻重复项

代码随想录算法训练营第十天 | 232.用栈实现队列, 225. 用队列实现栈, 20. 有效的括号 & 1047. 删除字符串中的所有相邻重复项

232. Implement Queue using Stacks

这一道题感觉有印象,但为了高效一点还是直接看了视频然后写的代码。
题目链接: 232. Implement Queue using Stacks
题目链接/文章讲解/视频讲解:代码随想录讲解

我的代码:
C++:

class MyQueue {
public:
    stack<int> stackIn;
    stack<int> stackOut;
    MyQueue() {
        
    }
    
    void push(int x) {
        stackIn.push(x);
    }
    
    int pop() {
        if (stackOut.empty()) {
            while (!stackIn.empty()) {
                stackOut.push(stackIn.top());
                stackIn.pop();
            }
        }
        int res = stackOut.top();
        stackOut.pop();
        return res;
    }
    
    int peek() {
        int res = this->pop();
        stackOut.push(res);
        return res;
    }
    
    bool empty() {
        return stackIn.empty() && stackOut.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();
 */

Python:

class MyQueue:

    def __init__(self):
        self.stackIn = []
        self.stackOut = []

    def push(self, x: int) -> None:
        self.stackIn.append(x)

    def pop(self) -> int:
        if not self.stackOut:
            while self.stackIn:
                self.stackOut.append(self.stackIn.pop())
        return self.stackOut.pop()

    def peek(self) -> int:
        res = self.pop()
        self.stackOut.append(res)
        return res

    def empty(self) -> bool:
        return not (self.stackIn or self.stackOut)


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

225. Implement Stack using Queues

这一道我是先看的视频,发现我做这一类实现某种数据结构类的题有些薄弱,其实不难,但是心理作用让我觉得很麻烦,每次看完视频都觉得完全没问题。
题目链接: 225. Implement Stack using Queues
题目链接/文章讲解/视频讲解:代码随想录讲解

我的代码:
Python:

class MyStack:

    def __init__(self):
        self.que = deque()

    def push(self, x: int) -> None:
        self.que.append(x)

    def pop(self) -> int:
        size = len(self.que) - 1
        while size:
            self.que.append(self.que.popleft())
            size -= 1
        
        return self.que.popleft()

    def top(self) -> int:
        size = len(self.que) - 1
        while size:
            self.que.append(self.que.popleft())
            size -= 1
        
        res = self.que.popleft()
        self.que.append(res)
        return res

    def empty(self) -> bool:
        return not self.que
        


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

C++:

class MyStack {
public:
    queue<int> que;
    MyStack() {
        
    }
    
    void push(int x) {
        que.push(x);
    }
    
    int pop() {
        int size = que.size();
        size--;
        while (size--) {
            que.push(que.front());
            que.pop();
        }
        int res = que.front();
        que.pop();
        return res;
    }
    
    int top() {
        return que.back();
    }
    
    bool empty() {
        return que.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. Valid Parentheses

这道题我用Python也顺利写出,但是思路被卡哥精准预判,我是把遍历到的符号一模一样的push进stack里,这不如push相对应的符号来的高效。于是在看完视频后C++的版本实现了卡哥的方法。
题目链接:20. Valid Parentheses
题目链接/文章讲解/视频讲解:代码随想录讲解

我的代码:
Python:

class Solution:
    def isValid(self, s: str) -> bool:
        stack = []

        for c in s:
            if c == "(" or c == "[" or c == "{":
                stack.append(c)
            else:
                if not stack:
                    return False
                cur = stack[-1]
                if cur == "(" and c == ")":
                    stack.pop()
                elif cur == "[" and c == "]":
                    stack.pop()
                elif cur == "{" and c == "}":
                    stack.pop()
                else:
                    return False
        
        return not stack


C++:

class Solution {
public:
    bool isValid(string s) {
        stack<int> st;
        for (char c : s) {
            if (c == '(') {
                st.push(')');
            } else if (c == '[') {
                st.push(']');
            } else if ( c == '{') {
                st.push('}');
            } else if (st.empty() || st.top() != c) {
                return false;
            } else {
                st.pop();
            }
        }
        return st.empty();
    }
};

1047. Remove All Adjacent Duplicates In String

这题用Python我可以轻松写出了!
然后看了视频读了读Carl的C++ solution,也成功写出了,用string模拟栈也太妙了!感觉C++还有很多很多需要掌握的地方
题目链接:LeetCode147
题目链接/文章讲解/视频讲解:代码随想录讲解

我的代码:
Python:

class Solution:
    def removeDuplicates(self, s: str) -> str:
        if not s or len(s) == 1:
            return s
        
        stack = []
        for c in s:
            if not stack:
                stack.append(c)
            elif stack[-1] == c:
                stack.pop()
            else:
                stack.append(c)
        
        return "".join(stack)

C++:

class Solution {
public:
    string removeDuplicates(string s) {
        // Time Complexity: O(n)
        // Space Complexity: O(1)
        string result;
        for (char c : s) {
            if (result.empty() || result.back() != c) {
                result.push_back(c);
            } else if (result.back() == c) {
                result.pop_back();
            }
        }
        return result;
    }
};

总结

感觉写栈相关的题目越来越游刃有余了,用到栈的题目也特别好identify!
队列比较不熟悉一些。
今天就写这么一点总结,赶进度加油!

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值