牛客 AB6 表达式求值 JAVA

描述

请写一个整数计算器,支持加减乘三种运算和括号。

数据范围:0≤∣�∣≤1000≤∣s∣≤100,保证计算结果始终在整型范围内

要求:空间复杂度: �(�)O(n),时间复杂度 �(�)O(n)

示例1

输入:

"1+2"

复制返回值:

3

 

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 返回表达式的值
     * @param s string字符串 待计算的表达式
     * @return int整型
     */
    HashMap<Character, Integer> map=new HashMap<Character,Integer>(){{
        put('-',1);
        put('+',1);
        put('*',2);
    }};
    public int solve (String s) {
        // write code here
        s=s.replaceAll(" ","");

        char[] cs=s.toCharArray();
        int n=s.length();
        Deque<Integer> nums=new ArrayDeque<>();

        nums.addLast(0);
        Deque<Character> ops=new ArrayDeque<>();

        for(int i=0;i<n;i++){
            char c=cs[i];
            if(c=='(') ops.addLast(c);
            else if(c==')'){
                while(!ops.isEmpty()){
                    if(ops.peekLast()!='(')
                    calc(nums,ops);
                else {
                    ops.pollLast();
                    break;
                }}
            }else {
                if(isNumber(c)){
                    int u=0;
                    int j=i;
                    while(j<n&&isNumber(cs[j])) u=u*10+(cs[j++]-'0');
                    nums.addLast(u);
                    i=j-1;
                }else {
                    if(i>0&&(cs[i-1]=='('||cs[i-1]=='+'||cs[i-1]=='-')) {
                        nums.addLast(0);
                    }
                    while(!ops.isEmpty()&&ops.peekLast()!='('){
                        char prev=ops.peekLast();
                        if(map.get(prev)>=map.get(c)){
                            calc(nums,ops);
                        }else break;
                    }
                    ops.addLast(c);
                }
            }
        }
        while(!ops.isEmpty()&&ops.peekLast()!='(') calc(nums,ops);
        return nums.peekLast();

    }
    void calc(Deque<Integer> nums,Deque<Character> ops){
        if(nums.isEmpty()||nums.size()<2) return ;
        if(ops.isEmpty()) return ;
        int b=nums.pollLast() , a=nums.pollLast();
        char op=ops.pollLast();
        int ans=0;
        if(op=='+') ans=a+b;
        else if(op=='-') ans=a-b;
        else if(op=='*') ans=a*b;
        nums.addLast(ans);
    }
    boolean isNumber(char c){
        return Character.isDigit(c);
    }






}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值