Calculator系列问题四 LeetCode 770. Basic Calculator IV

LeetCode 770. Basic Calculator IV

Given an expression such as expression = “e + 8 - a + 5” and an evaluation map such as {“e”: 1} (given in terms of evalvars = [“e”] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a",“14”]

An expression alternates chunks and symbols, with a space separating each chunk and symbol.
A chunk is either an expression in parentheses, a variable, or a non-negative integer.
A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like “2x” or “-x”.
Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. For example, expression = “1 + 2 * 3” has an answer of [“7”].

The format of the output is as follows:

For each term of free variables with non-zero coefficient, we write the free variables within a term in sorted order lexicographically. For example, we would never write a term like “bac”, only “abc”.
Terms have degree equal to the number of free variables being multiplied, counting multiplicity. (For example, “aabc" has degree 4.) We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed.
An example of a well formatted answer is ["-2
aaa”, “3aab", "3bb", "4a”, “5*c”, “-6”]
Terms (including constant terms) with coefficient 0 are not included. For example, an expression of “0” has an output of [].

Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output: ["-1*a","14"]

Input: expression = "e - 8 + temperature - pressure",
evalvars = ["e", "temperature"], evalints = [1, 12]
Output: ["-1*pressure","5"]

Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
Output: ["1*e*e","-64"]

Input: expression = "7 - 7", evalvars = [], evalints = []
Output: []

Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = []
Output: ["5*a*b*c"]

Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))",
evalvars = [], evalints = []
Output: ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c","1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b","2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"]

带变量的calculator,方法就是每个部分的数字变成了一个hashmap,存有数字和字母及其个数,逻辑上和前面的一样,但是hashmap的coding写起来很复杂,目前尚未完成,等有耐心了再回头看看吧,,,,

    public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {
        HashMap<String, Integer> dict = new HashMap<>();
        for (int i = 0; i < evalvars.length; i++) {
            dict.push(evalvars[i], evalints[i]);
        }
        HashMap<String, Integer> map = new HashMap<>();
        Stack<HashMap<String, Integer>> stack = new Stack<>();
        Stack<Character> sign = new Stack<>();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                int[] r = run(s, i);
                HashMap<String, Integer> cur = new HashMap<>();
                cur.add(r[0]+"", 1);
                if (!sign.isEmpty() && sign.peek().equals("*")){
                    sign.pop();
                    HashMap<String, Integer> pre = stack.pop();
                    HashMap<String, Integer> res = mulitply(cur, pre);
                    stack.push(res);
                } else {
                    stack.push(cur);
                }
                i = r[1];
            } else if (c == '+' || c == '-' || c == '*' || c =='(') {
                sign.push(c + "");
            } else if (c == ')') {
                HashMap<String, Integer> res = new HashMap<>();
                while (!sign.peek().equals("(")) {
                    HashMap<String, Integer> next = stack.pop();
                    if (stack.isEmpty() || sign.peek().equals("(")) {
                        res = next;
                        break;
                    }
                    String sign = stack.pop();
                    res = addOrMinus(res, next, sign);
                }
                sign.pop();
                stack.push(res);
                while (!stack.isEmpty() && (sign.peek().equals("*"))){
                    sign.pop();
                    HashMap<String, Integer> pre = stack.pop();
                    res = mulitply(res, pre);
                    stack.push(res);
                }
                
            } else if (c != ' '){
                int[] index = new int[]{i};
                String x = getString(s, index);
                if (dict.containsKey(x)) {
                    x = dict.get(x) + "";
                }
                HashMap<String, Integer> cur = new HashMap<>();
                cur.add(x, 1);
                if (!sign.isEmpty() && sign.peek().equals("*")){
                    sign.pop();
                    HashMap<String, Integer> pre = stack.pop();
                    HashMap<String, Integer> res = mulitply(cur, pre);
                    stack.push(res);
                } else {
                    stack.push(cur);
                }
                i = index[0];
            }
        }
        return getFinalResult(stack);
    }
    private HashMap<String, Integer> addOrMinus(HashMap<String, Integer> res, HashMap<String, Integer> next, String sign) {
        if (sign.equals("-")) {
            for (String s : next.keySet()) {
                res.push(s, res.getOrDefault(s, 0) + next.get(s) * (-1));
            }
        } else {
            for (String s : next.keySet()) {
                res.push(s, res.getOrDefault(s, 0) + next.get(s));
            }
        }
        return res;
    }
    private List<String> getFinalResult(Stack<HashMap<String, Integer>> stack) {
        List<String> res = new ArrayList<>();
        String last = "";
        while (!stack.isEmpty()) {
            int next = Integer.parseInt(stack.pop());
            if (stack.isEmpty()) return (result + next);
            String sign = stack.pop();
            if (sign.equals("+")) result += next;
            else result -= next;
            
        }
        return 0;
    }
    private String getString(String s, int[] i) {
        StringBuilder res = new StringBuilder();
        while (i[0] < s.length() && (s.charAt(i[0]) != '+') && s.charAt(i[0]) != '-') && s.charAt(i[0]) != '*') && s.charAt(i[0]) != '(') && s.charAt(i[0]) != ')') && s.charAt(i[0]) != ' ')) {
            res.append(s.charAt(i[0]));
            i[0]++;
        }
        i[0]--;
        return res;
    }
    private int[] run(String s, int i) {
        int[] res = new int[2];
        while (i < s.length() && Character.isDigit(s.charAt(i))) {
            res[0] = res[0] * 10 + s.charAt(i++) - '0';
        }
        res[1] = i - 1;
        return res;
    }
    private HashMap<String, Integer> multiply(HashMap<String, Integer> cur, HashMap<String, Integer> pre) {
        HashMap<String, Integer> res = new HashMap<>();
        for (String s1 : pre.keySet()) {
            for (String s2 : cur.keySet()) {
                if (Character.isDigit(s1.charAt(0)) && Character.isDigit(s2.charAt(0))) {
                    res.push(Integer.parseInt(s1) * Integer.parseInt(s2) * cur.get(s2) * pre.get(s1), 1);
                } else if (Character.isDigit(s1.charAt(0))) {
                    res.push(s2, res.getOrDefault(s2, 0) + Integer.parseInt(s1) * pre.get(s1) * cur.get(s2));
                } else if (Character.isDigit(s2.charAt(0))) {
                    res.push(s1, res.getOrDefault(s1, 0) + Integer.parseInt(s2) * cur.get(s2) * pre.get(s1));
                } else {
                    PriorityQueue<String> q = new PriorityQueue<>();
                    String[] ss = s1.split("\\*");
                    for (String cur : ss) q.offer(cur);
                    ss = s2.split("\\*");
                    for (String cur : ss) q.offer(cur);
                    StringBuilder sb = new StringBuilder();
                    while (!q.isEmpty()) {
                        sb.append(q.poll()).append("*");
                    }
                    sb.remove(sb.length() - 1);
                    res.push(sb.toString(), res.getOrDefault(sb.toString(), 0) + pre.get(s1) * cur.get(s2));
                }
            }
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值