227. Basic Calculator II

本文探讨了如何利用栈数据结构高效地解决含有加减乘除运算的算术表达式计算问题。通过三次代码实现迭代,从初步尝试到逐步优化,最终形成了简洁且高效的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

三刷。

这次尝试把代码写的美观一些。。。

还是用stack,乘除就POP出一个再运算入栈,否则直接入栈。因为要运算,所以要记录上一个运算符号,第一个是+,因为STACK里所有的值都是+。

Time: O(n)

Space: O(n)

public class Solution {
    public int calculate(String s) {
        if (s.length() == 0) return 0;
        
        Stack<Integer> stk = new Stack<>();
        int temp = 0;
        char sign = '+';
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                temp = 10 * temp + c - '0';
            }
            if ((!Character.isDigit(c) && c != ' ') || i == s.length() - 1) {
                switch (sign) {
                    case '+':
                        stk.push(temp);
                        break;
                    case '-':
                        stk.push(-temp);
                        break;
                    case '*':
                        stk.push(stk.pop() * temp);
                        break;
                    case '/':
                        stk.push(stk.pop() / temp);
                        break;
                    default:
                        break;
                }
                sign = c;
                temp = 0;
            }
            
        } 
        
        int res = 0;
        while (!stk.isEmpty()) {
            res += stk.pop();
        }
        
        return res;
    }
}

二刷。

报警了,改了好几次。

二刷所有CASE都想到了,一开始没看到是NON-NEGATIVE还考虑了负数怎么办。

可能因为二刷的时候有点印象,二刷确实是改进了一刷的很多地方。诸如 只存入Integer

public class Solution 
{
    public int calculate(String s) 
    {
        int res = 0;
        
        if(s.length() <= 2) return Integer.valueOf(s);
        
        Stack<Integer> stk = new Stack<>();
        int tempVal = 0;
        char last = '+';
        stk.push(0);
        for(int i = 0;  i<s.length();i++)
        {
            char tempCh = s.charAt(i);
            if(tempCh >= '0' && tempCh <= '9')
            {
                tempVal = 10*tempVal + tempCh - '0';
                
            }
            else if(tempCh == ' ') continue;
            else
            {
                if(last == '+')
                {
                    stk.push(tempVal);
                }
                else if(last == '-')
                {
                    stk.push(0-tempVal);
                }
                else if(last == '*')
                {
                    stk.push(tempVal * stk.pop());
                }
                else
                {
                    stk.push(stk.pop() / tempVal);
                }
                tempVal = 0;
                last = tempCh;
   
            }
        }
        
                if(last == '+')
                {
                    stk.push(tempVal);
                }
                else if(last == '-')
                {
                    stk.push(0-tempVal);
                }
                else if(last == '*')
                {
                    stk.push(tempVal * stk.pop());
                }
                else
                {
                    stk.push(stk.pop() / tempVal);
                }
        
        
        
        while(!stk.isEmpty())
        {
            res += stk.pop();
        }
        return res;
        
        
    }
}

感觉上没什么难的,似乎是用STACK就可以,因为只有2级运算。

一开始往STACK里添加,数字就加,+-也加,碰到*/就POP一个出来运算,运算完的数字夹进去。

最后STACK里只有1级运算。 然后2个2个往外取,POP的第一个是符号,POP的第二个是数,这样不用REVERSE STACK了

public int calculate(String s) {
        
        Stack<String> stack = new Stack<String>();

        String temp = new String("");
        for(int n = 0; n < s.length();n++)
        {
            
            char ch = s.charAt(n);
            if(ch == '*')
            {
                int int1 = Integer.valueOf(temp);
                temp = new String();
                n++;
                while(!(s.charAt(n)=='+' || s.charAt(n)=='-' ||s.charAt(n)=='/' ||s.charAt(n)=='*') && n<s.length())
                {
                    if(s.charAt(n)!=' ')
                    temp = temp+s.charAt(n);
                    n++;
                    if(n == s.length()) break;
                }
                n--;
                int int2 = Integer.valueOf(temp);
                temp = new String();
                
                
                int tempInt = int1 * int2;
                temp = new String(Integer.toString(tempInt));


            }
            else if (ch == '/')
            {
                int int1 = Integer.valueOf(temp);
                temp = new String();
                n++;
                while(!(s.charAt(n)=='+' || s.charAt(n)=='-' ||s.charAt(n)=='/' ||s.charAt(n)=='*') && n<s.length())
                {
                    if(s.charAt(n)!=' ')
                    temp = temp+s.charAt(n);
                    n++;
                    if(n == s.length()) break;
                }
                n--;
                int int2 = Integer.valueOf(temp);
                temp = new String();
                
                
                int tempInt = int1 / int2;
                temp = new String(Integer.toString(tempInt));
            }
            else if (ch == '+')
            {
                stack.push(temp);
                stack.push("+");
                temp = new String("");
            }
            else if(ch == '-')
            {
                stack.push(temp);
                stack.push("-");
                temp = new String("");
            }
            else if(ch == ' ')
            {
                
            }
            else
            {
                temp = temp + ch;

            }
        }       
        
        Stack<String> resStack = new Stack<String>();
        
        resStack.push(temp);

        while(stack.size()>0)
        {

            resStack.push(stack.pop());
        }
        int res = Integer.valueOf(resStack.pop());
        while(resStack.size()>0)
        {

            char tempCh = resStack.pop().charAt(0);

            int firstInt = Integer.valueOf(resStack.pop());
            if(tempCh == '+') res = firstInt + res;
            else res = res - firstInt;
        }

        return res;
    }

写起来比想象的难多了。。各种CASE都没有考虑到。。

改了100遍。。。。。。。

有2点可以改进的地方
1个是可以用10 100 来添加多位数,不一定非要用数组各种转换。。

另一个是 -X 可以 把(-x)作为一个值放到STACK里
+负数其实就是- 这样的话STACK里可以全是INT了

然后各种CASE太多了。。二刷改进

转载于:https://www.cnblogs.com/reboot329/p/6144483.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值