NC137 表达式求值

NC137 表达式求值

描述
请写一个整数计算器,支持加减乘三种运算和括号。
示例1
输入:
“1+2”
复制
返回值:
3
复制
示例2
输入:
“(2*(3-4))5"
复制
返回值:
-10
复制
示例3
输入:
"3+2
3*4-1”
复制
返回值:
26

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 返回表达式的值
     * @param s string字符串 待计算的表达式
     * @return int整型
     */
    public int solve (String s) {
        // write code here
        Stack<Integer> nums = new Stack<>();
        Stack<Character> ops = new Stack<>();
        Map<Character , Integer> map = new HashMap<>();
        map.put('+' , 1) ;
        map.put('-' , 1) ;
        map.put('*' , 2) ;
        for(int i = 0 ; i < s.length() ; i++){
            char curt = s.charAt(i) ;
            if(Character.isDigit(curt)){
                String num = String.valueOf(curt) ;
                while(++i < s.length()){
                    char temp = s.charAt(i);
                    if(Character.isDigit(temp)){
                        num += temp ;
                    }else{
                        break ;
                    }
                    //i++ ;
                }
                nums.push(Integer.valueOf(num)) ;
                i-- ;
                continue ;
            }
            if(ops.isEmpty()){
                ops.push(curt) ;
                continue ;
            }
            if(curt == '('){
                ops.push(curt) ;
                continue ;
            }
            if(curt == ')'){
                while(ops.peek() != '('){
                    char ope = ops.pop();
                    cal(nums , ope) ;
                }
                ops.pop() ;
                continue ;
            }
            while(!ops.isEmpty() && (map.getOrDefault(ops.peek(), 0) >= map.get(curt))){
                char lastop = ops.peek() ;
                ops.pop();
                cal(nums , lastop) ;
            }
            ops.push(curt) ;
            
        }
        while(!ops.isEmpty()){
            cal(nums , ops.pop()) ;
        }
        return nums.pop() ;
        
    }
    public void cal(Stack<Integer> nums , char lastop){
        int num1 = nums.pop() ;
        int num2 = nums.pop();
        int ans = 0 ;
        if(lastop == '*'){
            ans = num1 * num2 ;
        }
        if(lastop == '+'){
            ans = num1 + num2 ;
        }
        if(lastop == '-'){
            ans = num2 - num1 ;
        }
        nums.push(ans) ;
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值