代码随想录10| 20. 有效的括号, 1047. 删除字符串中的所有相邻重复项, 150. 逆波兰表达式求值

20. 有效的括号

题目链接/文章讲解/视频讲解:链接地址

代码思路:利用栈的先进后出原则,分析题目可知,如果遍历字符串,往栈压字符,必定是成对的出现在栈里面,这种思维类似与消消乐,如果栈里面没有成对出现的字符,就返回false,最后栈里面都是空返回true.

class Solution {
public:
    bool isValid(string s) {
        stack<char> tempStack;
        if (s.size() % 2 != 0) {
            return false;
        }
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(') tempStack.push(')');
            else if (s[i] == '[') tempStack.push(']');
            else if (s[i] == '{') tempStack.push('}');
            else if (tempStack.empty() || tempStack.top() != s[i]) return false;
            else tempStack.pop();
        }
        if (tempStack.empty()) {
            return true;
        } else {
            return false;
        }

    }
};

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

题目链接/文章讲解/视频讲解:链接地址

代码思路:创建一个栈,遍历整个字符串,与栈顶的数据进行对比,如果相同就pop出来,如果不同就push进栈。最后对栈里面剩余的元素反转返回就是结果。

class Solution {
public:
    string removeDuplicates(string s) {
        stack<char> tempStack;
        for (int i = 0; i < s.size(); i++) {
            if (tempStack.empty() || tempStack.top() != s[i]) {
                tempStack.push(s[i]);
            } else {
                tempStack.pop();
            }
        }

        string result = "";
        while (!tempStack.empty()) {
            result += tempStack.top();
            tempStack.pop();
        }
        reverse (result.begin(), result.end());
        return result;

    }
};

150. 逆波兰表达式求值

题目链接/文章讲解/视频讲解:链接地址

代码思路:通过观察分析得出,数组里面的元素遇到数学运算符号的时候就将运算符号前面的两个进行相应的运算,因此可以通过栈的特性来实现代码。

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<long long> tempStack;//测试用例需要用到这么大的数据类型

        for (int i = 0; i < tokens.size(); i++) {
            if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {
                long long nums1 = tempStack.top();
                tempStack.pop();
                long long nums2 = tempStack.top();
                tempStack.pop();
                if (tokens[i] == "+") tempStack.push(nums2 + nums1);
                if (tokens[i] == "-") tempStack.push(nums2 - nums1);
                if (tokens[i] == "*") tempStack.push(nums2 * nums1);
                if (tokens[i] == "/") tempStack.push(nums2 / nums1);// 注意是nums2 在前面
            } else {
                tempStack.push(stoll(tokens[i]));
            }
        }
        int result = tempStack.top();
        return result;


    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值