代码随想录算法训练营第十一天 | 20.有效的括号 1047.删除字符串中的所有相邻 重复项 150.逆波兰表达式求值

20. 有效的括号

题目链接 文章讲解 视频讲解

思路:遍历字符串,如果栈不为空,则进行匹配
   如果匹配则出栈,否则入栈
   如果栈为空,直接入栈
   遍历结束后栈为空则说明全部匹配,否则没有全部匹配

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

            } else {
                st.push(ch);
            }
        } 
        return st.empty();  
    }
};

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

题目链接 文章讲解 视频讲解

思路:同上一题,不过这次是字符相同出栈

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> st;
        for(char ch : s) {
            if(!st.empty()) {
                if(st.top() == ch) st.pop();
                else st.push(ch);
            } else {
                st.push(ch);
            }
        }
        int size = st.size();
        s.resize(size);
        while(!st.empty()) {
            s[--size] = st.top();
            st.pop();
        }
        return s;
    }
};

150. 逆波兰表达式求值

题目链接 文章讲解 视频讲解

后缀表达式,直接用栈来解,唯一要注意的就是先出栈的元素是表达式右边的操作数

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> st;
        int ans;
        int rhs;
        int lhs;
        for(string s : tokens) {
            if(s != "+" && s != "*" && s != "-" && s != "/") {
                st.push(stoi(s));
            } else {
                rhs = st.top();
                st.pop();
                lhs = st.top();
                st.pop();
                switch (s[0]) {
                case '+' :
                    ans = lhs + rhs;
                    break;
                case '-' :
                    ans = lhs - rhs;
                    break;
                case '*' :
                    ans = lhs * rhs;
                    break;
                case '/' :
                    ans = lhs / rhs;
                    break;
                }
                st.push(ans);
            }
        }
    
        return st.top();
    }
};
posted @ 2024-05-18 16:00  深蓝von  阅读(2)  评论(0编辑  收藏  举报