题解 | #表达式求值#

表达式求值

https://www.nowcoder.com/practice/c215ba61c8b1443b996351df929dc4d4

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * 返回表达式的值
     * @param s string字符串 待计算的表达式
     * @return int整型
     */
    public int solve (String s) {
        // write code here
        //map:操作符优先级
        Map<Character, Integer> map = new HashMap<>();
        map.put('+', 1);
        map.put('-', 1);
        map.put('*', 2);
        //num:存放数字
        Stack<Integer> num = new Stack<>();
        //fuhao:存放操作符
        Stack<Character> fuhao = new Stack<>();
        String x = "";
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == ' ')
                continue;
            if (ch == '(') {
                //直接存入(
                fuhao.push(ch);
            } else if (ch == '+' || ch == '*' || ch == '-') {
                //计算比ch优先级高的
                while (!fuhao.isEmpty() && fuhao.peek() != '(' && map.get(fuhao.peek()) >= map.get(ch)) {
                    fun(num, fuhao);
                }
                fuhao.push(ch);
            } else if (ch == ')') {
                //计算括号里的
                while (!fuhao.isEmpty() && fuhao.peek() != '(') {
                    fun(num, fuhao);
                }
                fuhao.pop();
            } else {
                //处理数字
                x = "";
                int j = i;
                for (j = i; j < s.length(); j++) {
                    char c = s.charAt(j);
                    if (c >= '0' && c <= '9') {
                        x += c;
                    } else {
                        break;
                    }
                }
                i = j - 1;
                if (x.length() > 0)
                num.push(Integer.parseInt(x));
            }
        }
        while(!fuhao.isEmpty()) {
            fun(num, fuhao);
        }
        return num.pop();
    }
    
    //运算
    public void fun(Stack<Integer> num, Stack<Character> fuhao) {
        char c = fuhao.pop();
        int b = num.pop();
        int a = num.pop();
        if (c == '+') {
            num.push(a + b);
        } else if (c == '-'){
            num.push(a - b);
        } else {
            num.push(a * b);
        }
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务