youngyangyang04 / leetcode-master-comment

用来做评论区
0 stars 0 forks source link

[Vssue]0150.逆波兰表达式求值.md #46

Open youngyangyang04 opened 4 months ago

youngyangyang04 commented 4 months ago

https://programmercarl.com/0150.%E9%80%86%E6%B3%A2%E5%85%B0%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%B1%82%E5%80%BC.html

yuyuanyuanhua commented 4 months ago

如果增加一个字符代码要怎么写呢,就是每三个连续相等的字符就消除,剩余的拼接在一起再有三个连续相等继续消除。 如输入abbbacaaa,输出aac

Veritas2024 commented 3 months ago

@yuyuanyuanhua

如果增加一个字符代码要怎么写呢,就是每三个连续相等的字符就消除,剩余的拼接在一起再有三个连续相等继续消除。 如输入abbbacaaa,输出aac

当栈内元素小于2时直接向栈中添加元素,当栈的元素大于等于2时,判断当前元素是否同时和栈最上面的两个元素相同(先弹出一次栈顶元素得到第二个元素),如果相同则将将这两个元素都弹出,否则将当前元素入栈。由这种方法可以推广到连续N个相等的元素就消除的情形。

Du1in9 commented 2 months ago
class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> st = new Stack<>();
        for (String t : tokens) {
            if (t.equals("+") || t.equals("-") || t.equals("*") || t.equals("/")) {
                int x = st.pop();
                int y = st.pop();
                if (t.equals("+")) st.push(y + x);
                if (t.equals("-")) st.push(y - x);
                if (t.equals("*")) st.push(y * x);
                if (t.equals("/")) st.push(y / x);
            } else {
                st.push(Integer.parseInt(t));
            }
        }
        return st.pop();
    }
}
ImaginDragon-Ma commented 1 month ago

这里为什么要有long long类型呢,10^4大小int就行了吧