LeetCode(八)栈相关-#224

224. 基本计算器

1.题目描述及示例

  1. 题目描述
    实现一个基本的计算器来计算一个简单的字符串表达式的值。
    字符串表达式可以包含左括号 ( ,右括号 ),加号 + ,减号 -,非负整数和空格 。

  2. 示例
    在这里插入图片描述

2.题解思路及代码

  1. 思路
    参考《算法笔记》中,关于栈这节的内容
  2. 代码
    public int calculate(String s) {
        s=s.trim();
        int [] nums=new int[s.length()];
        int [] ops=new int[s.length()];
        int numsIndex=-1,opsIndex=-1;
        for(int i=0;i<s.length();i++)
        {
            char c=s.charAt(i);

            if (c>='0'&&c<='9')
            {
                int temp=0;
                int j=i;
                while (c>='0'&&c<='9')
                {
                    temp=temp*10+c-'0';
                    j++;
                    if (j==s.length())
                        break;
                    c=s.charAt(j);
                }
                numsIndex++;
                nums[numsIndex]=temp;
                i=j-1;
            }
            else if (c=='-'||c=='+')
            {
                while (opsIndex!=-1&&ops[opsIndex]!=-1)
                {
                    numsIndex++;
                    nums[numsIndex]=ops[opsIndex];
                    opsIndex--;
                }
                if (opsIndex==-1||ops[opsIndex]==-1)
                {
                    opsIndex++;
                    if (c=='-')
                        ops[opsIndex]=-3;
                    else
                        ops[opsIndex]=-2;
                }
            }
            else if (c=='(')
            {
                opsIndex++;
                ops[opsIndex]=-1;
            }
            else if (c==')')
            {
                while (ops[opsIndex]!=-1)
                {
                    numsIndex++;
                    nums[numsIndex]=ops[opsIndex];
                    opsIndex--;
                }
                opsIndex--;
            }
        }
        while (opsIndex!=-1)
        {
            numsIndex++;
            nums[numsIndex]=ops[opsIndex];
            opsIndex--;
        }
        Stack<Integer>stack=new Stack<Integer>();
        for (int i=0;i<=numsIndex;i++)
        {
            if (nums[i]!=-3&&nums[i]!=-2)
            {
                stack.push(nums[i]);
            }
            else
            {
                int b=stack.pop();
                int a=stack.pop();
                if (nums[i]==-2)
                    stack.push(a+b);
                else
                    stack.push(a-b);
            }
        }

        return stack.pop();
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值