加载中...
770-基本计算器 IV(Basic Calculator IV)
发表于:2021-12-03 | 分类: 困难
字数统计: 2.8k | 阅读时长: 15分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/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 a non-zero coefficient, we write the free variables within a term in sorted order lexicographically.
    • For example, we would never write a term like "b*a*c", only "a*b*c".
  • Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
    • For example, "a*a*b*c" has degree 4.
  • 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*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"].
  • Terms (including constant terms) with coefficient 0 are not included.
    • For example, an expression of "0" has an output of [].

 

Example 1:

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

Example 2:

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

Example 3:

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

Example 4:

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

Example 5:

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"]

 

Constraints:

  • 1 <= expression.length <= 250
  • expression consists of lowercase English letters, digits, '+', '-', '*', '(', ')', ' '.
  • expression does not contain any leading or trailing spaces.
  • All the tokens in expression are separated by a single space.
  • 0 <= evalvars.length <= 100
  • 1 <= evalvars[i].length <= 20
  • evalvars[i] consists of lowercase English letters.
  • evalints.length == evalvars.length
  • -100 <= evalints[i] <= 100

中文题目

给定一个表达式 expression 如 expression = "e + 8 - a + 5" 和一个求值映射,如 {"e": 1}(给定的形式为 evalvars = ["e"] 和 evalints = [1]),返回表示简化表达式的标记列表,例如 ["-1*a","14"]

  • 表达式交替使用块和符号,每个块和符号之间有一个空格。
  • 块要么是括号中的表达式,要么是变量,要么是非负整数。
  • 块是括号中的表达式,变量或非负整数。
  • 变量是一个由小写字母组成的字符串(不包括数字)。请注意,变量可以是多个字母,并注意变量从不具有像 "2x" 或 "-x" 这样的前导系数或一元运算符 。

表达式按通常顺序进行求值:先是括号,然后求乘法,再计算加法和减法。例如,expression = "1 + 2 * 3" 的答案是 ["7"]

输出格式如下:

  • 对于系数非零的每个自变量项,我们按字典排序的顺序将自变量写在一个项中。例如,我们永远不会写像 “b*a*c” 这样的项,只写 “a*b*c”
  • 项的次数等于被乘的自变量的数目,并计算重复项。(例如,"a*a*b*c" 的次数为 4。)。我们先写出答案的最大次数项,用字典顺序打破关系,此时忽略词的前导系数。
  • 项的前导系数直接放在左边,用星号将它与变量分隔开(如果存在的话)。前导系数 1 仍然要打印出来。
  • 格式良好的一个示例答案是 ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] 。
  • 系数为 0 的项(包括常数项)不包括在内。例如,“0” 的表达式输出为 []。

 

示例:

输入:expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
输出:["-1*a","14"]

输入:expression = "e - 8 + temperature - pressure",
evalvars = ["e", "temperature"], evalints = [1, 12]
输出:["-1*pressure","5"]

输入:expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
输出:["1*e*e","-64"]

输入:expression = "7 - 7", evalvars = [], evalints = []
输出:[]

输入:expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = []
输出:["5*a*b*c"]

输入:expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))",
evalvars = [], evalints = []
输出:["-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"]

 

提示:

  1. expression 的长度在 [1, 250] 范围内。
  2. evalvars, evalints 在范围 [0, 100] 内,且长度相同。

通过代码

官方题解

方法一: 多项式类 【通过】

思路

构建一个 Poly 多项式类,实现这个多项式类的一些数学操作。

算法

单独实现每个方法都很直接,这里先列一下要实现的方法:

  • Poly:add(this, that) 返回 this + that 的结果。

  • Poly:sub(this, that) 返回 this - that 的结果。

  • Poly:mul(this, that) 返回 this * that 的结果。

  • Poly:evaluate(this, evalmap) 返回将所有的自由变量替换成 evalmap 指定常数之后的结果。

  • Poly:toList(this) 返回正确的多项式输出格式。

  • Solution::combine(left, right, symbol) 返回对 左边(left)右边(left) 进行 symobl 操作之后的结果。

  • Solution::make(expr) 创造一个新的 Poly 实例来表示常数或 expr 指定的变量。

  • Solution::parse(expr)expr 解析成一个 Poly 实例。

[solution1-Python]
class Poly(collections.Counter): def __add__(self, other): self.update(other) return self def __sub__(self, other): self.update({k: -v for k, v in other.items()}) return self def __mul__(self, other): ans = Poly() for k1, v1 in self.items(): for k2, v2 in other.items(): ans.update({tuple(sorted(k1 + k2)): v1 * v2}) return ans def evaluate(self, evalmap): ans = Poly() for k, c in self.items(): free = [] for token in k: if token in evalmap: c *= evalmap[token] else: free.append(token) ans[tuple(free)] += c return ans def to_list(self): return ["*".join((str(v),) + k) for k, v in sorted(self.items(), key = lambda (k, v): (-len(k), k, v)) if v] class Solution(object): def basicCalculatorIV(self, expression, evalvars, evalints): evalmap = dict(zip(evalvars, evalints)) def combine(left, right, symbol): if symbol == '+': return left + right if symbol == '-': return left - right if symbol == '*': return left * right raise def make(expr): ans = Poly() if expr.isdigit(): ans.update({(): int(expr)}) else: ans[(expr,)] += 1 return ans def parse(expr): bucket = [] symbols = [] i = 0 while i < len(expr): if expr[i] == '(': bal = 0 for j in xrange(i, len(expr)): if expr[j] == '(': bal += 1 if expr[j] == ')': bal -= 1 if bal == 0: break bucket.append(parse(expr[i+1:j])) i = j elif expr[i].isalnum(): for j in xrange(i, len(expr)): if expr[j] == ' ': bucket.append(make(expr[i:j])) break else: bucket.append(make(expr[i:])) i = j elif expr[i] in '+-*': symbols.append(expr[i]) i += 1 for i in xrange(len(symbols) - 1, -1, -1): if symbols[i] == '*': bucket[i] = combine(bucket[i], bucket.pop(i+1), symbols.pop(i)) if not bucket: return Poly() ans = bucket[0] for i, symbol in enumerate(symbols, 1): ans = combine(ans, bucket[i], symbol) return ans P = parse(expression).evaluate(evalmap) return P.to_list()
[solution1-Java]
class Solution { public List<String> basicCalculatorIV(String expression, String[] evalVars, int[] evalInts) { Map<String, Integer> evalMap = new HashMap(); for (int i = 0; i < evalVars.length; ++i) evalMap.put(evalVars[i], evalInts[i]); return parse(expression).evaluate(evalMap).toList(); } public Poly make(String expr) { Poly ans = new Poly(); List<String> list = new ArrayList(); if (Character.isDigit(expr.charAt(0))) { ans.update(list, Integer.valueOf(expr)); } else { list.add(expr); ans.update(list, 1); } return ans; } public Poly combine(Poly left, Poly right, char symbol) { if (symbol == '+') return left.add(right); if (symbol == '-') return left.sub(right); if (symbol == '*') return left.mul(right); throw null; } public Poly parse(String expr) { List<Poly> bucket = new ArrayList(); List<Character> symbols = new ArrayList(); int i = 0; while (i < expr.length()) { if (expr.charAt(i) == '(') { int bal = 0, j = i; for (; j < expr.length(); ++j) { if (expr.charAt(j) == '(') bal++; if (expr.charAt(j) == ')') bal--; if (bal == 0) break; } bucket.add(parse(expr.substring(i+1, j))); i = j; } else if (Character.isLetterOrDigit(expr.charAt(i))) { int j = i; search : { for (; j < expr.length(); ++j) if (expr.charAt(j) == ' ') { bucket.add(make(expr.substring(i, j))); break search; } bucket.add(make(expr.substring(i))); } i = j; } else if (expr.charAt(i) != ' ') { symbols.add(expr.charAt(i)); } i++; } for (int j = symbols.size() - 1; j >= 0; --j) if (symbols.get(j) == '*') bucket.set(j, combine(bucket.get(j), bucket.remove(j+1), symbols.remove(j))); if (bucket.isEmpty()) return new Poly(); Poly ans = bucket.get(0); for (int j = 0; j < symbols.size(); ++j) ans = combine(ans, bucket.get(j+1), symbols.get(j)); return ans; } } class Poly { HashMap<List<String>, Integer> count; Poly() {count = new HashMap();} void update(List<String> key, int val) { this.count.put(key, this.count.getOrDefault(key, 0) + val); } Poly add(Poly that) { Poly ans = new Poly(); for (List<String> k: this.count.keySet()) ans.update(k, this.count.get(k)); for (List<String> k: that.count.keySet()) ans.update(k, that.count.get(k)); return ans; } Poly sub(Poly that) { Poly ans = new Poly(); for (List<String> k: this.count.keySet()) ans.update(k, this.count.get(k)); for (List<String> k: that.count.keySet()) ans.update(k, -that.count.get(k)); return ans; } Poly mul(Poly that) { Poly ans = new Poly(); for (List<String> k1: this.count.keySet()) for (List<String> k2: that.count.keySet()) { List<String> kNew = new ArrayList(); for (String x: k1) kNew.add(x); for (String x: k2) kNew.add(x); Collections.sort(kNew); ans.update(kNew, this.count.get(k1) * that.count.get(k2)); } return ans; } Poly evaluate(Map<String, Integer> evalMap) { Poly ans = new Poly(); for (List<String> k: this.count.keySet()) { int c = this.count.get(k); List<String> free = new ArrayList(); for (String token: k) { if (evalMap.containsKey(token)) c *= evalMap.get(token); else free.add(token); } ans.update(free, c); } return ans; } int compareList(List<String> A, List<String> B) { int i = 0; for (String x: A) { String y = B.get(i++); if (x.compareTo(y) != 0) return x.compareTo(y); } return 0; } List<String> toList() { List<String> ans = new ArrayList(); List<List<String>> keys = new ArrayList(this.count.keySet()); Collections.sort(keys, (a, b) -> a.size() != b.size() ? b.size() - a.size() : compareList(a, b)); for (List<String> key: keys) { int v = this.count.get(key); if (v == 0) continue; StringBuilder word = new StringBuilder(); word.append("" + v); for (String token: key) { word.append('*'); word.append(token); } ans.add(word.toString()); } return ans; } }

复杂度分析

  • 时间复杂度: 时间复杂度即为 $O(2^N + M)$,其中 $N$ 为 expression 的长度, $M$ 为 evalvarsevalints 的长度。

  • 空间复杂度: $O(N + M)$。

统计信息

通过次数 提交次数 AC比率
1261 2253 56.0%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言

相似题目

题目 难度
Lisp 语法解析 困难
基本计算器 III 困难
上一篇:
769-最多能完成排序的块(Max Chunks To Make Sorted)
下一篇:
700-二叉搜索树中的搜索(Search in a Binary Search Tree)
本文目录
本文目录