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 "b*a*c", only "a*b*c".
  • Terms have degree equal to the number of free variables being multiplied, counting multiplicity. (For example, "a*a*b*c"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*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 [].

Examples:

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

Note:

  1. expression will have length in range [1, 250].
  2. evalvars, evalints will have equal lengths in range [0, 100].

Approach #1: Simulate. [Java]

class Solution {
Map<String, Integer> map = new HashMap<>();
class Term {
int para = 1;
List<String> var = new ArrayList<>();
@Override
public String toString() {
if (para == 0) return "";
String ans = "";
for (String s : var) ans += "*" + s;
return para + ans;
} boolean equals(Term that) {
if (this.var.size() != that.var.size()) return false;
for (int i = 0; i < this.var.size(); ++i)
if (!this.var.get(i).equals(that.var.get(i))) return false;
return true;
} int compareTo(Term that) {
if (this.var.size() > that.var.size()) return -1;
if (this.var.size() < that.var.size()) return 1;
for (int i = 0; i < this.var.size(); ++i) {
int x = this.var.get(i).compareTo(that.var.get(i));
if (x != 0) return x;
}
return 0;
} Term times(Term that) {
Term pro = new Term(this.para * that.para);
for (String s : this.var) pro.var.add(new String(s));
for (String s : that.var) pro.var.add(new String(s));
Collections.sort(pro.var);
return pro;
} Term (int x) { para = x; }
Term (String s) {
if (map.containsKey(s)) para = map.get(s);
else var.add(s);
}
Term (Term that) {
this.para = that.para;
this.var = new ArrayList<>(that.var);
}
} class Expression {
List<Term> list = new ArrayList<>();
char oper = '+';
Expression(int x) { list.add(new Term(x)); }
Expression(String s) { list.add(new Term(s)); }
Expression(List<Term> l) { list = l; } Expression times(Expression that) {
List<Term> c = new ArrayList<>();
for (Term t1 : this.list)
for (Term t2 : that.list)
c.add(t1.times(t2));
c = combine(c);
return new Expression(c);
} Expression plus(Expression that, int sgn) {
List<Term> c = new ArrayList<>();
for (Term t : this.list) c.add(new Term(t));
for (Term t : that.list) {
Term t2 = new Term(t);
t2.para = t2.para * sgn;
c.add(t2);
}
c = combine(c);
return new Expression(c);
} Expression cal(Expression that) {
if (oper == '+') return plus(that, 1);
if (oper == '-') return plus(that, -1);
return times(that);
} List<String> toList() {
List<String> ans = new ArrayList<>();
for (Term t : list) {
String s = t.toString();
if (s.length() > 0) ans.add(s);
}
return ans;
} List<Term> combine(List<Term> a) {
Collections.sort(a, (t1, t2)->(t1.compareTo(t2)));
List<Term> c = new ArrayList<>();
for (Term t : a) {
if (c.size() != 0 && t.equals(c.get(c.size() - 1)))
c.get(c.size() - 1).para += t.para;
else
c.add(new Term(t));
}
return c;
}
} public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) {
for (int i = 0; i < evalvars.length; ++i)
map.put(evalvars[i], evalints[i]);
int i = 0, l = expression.length();
Stack<Expression> stack = new Stack<>();
Stack<Integer> priStack = new Stack<>();
Expression zero = new Expression(0);
stack.push(zero);
priStack.push(0);
int pri = 0;
while (i < l) {
char ch = expression.charAt(i);
if (Character.isDigit(ch)) {
int num = 0;
while (i < l && Character.isDigit(expression.charAt(i))) {
num = num * 10 + (expression.charAt(i) - 48);
i++;
}
stack.add(new Expression(num));
continue;
}
if (Character.isLetter(ch)) {
String s = "";
while (i < l && Character.isLetter(expression.charAt(i))) {
s += expression.charAt(i);
i++;
}
stack.add(new Expression(s));
continue;
}
if (ch == '(') pri += 2;
if (ch == ')') pri -= 2;
if (ch == '+' || ch == '-' || ch == '*') {
int nowPri = pri;
if (ch == '*') nowPri++;
while (!priStack.isEmpty() && nowPri < priStack.peek()) {
Expression now = stack.pop(), last = stack.pop();
priStack.pop();
stack.push(last.cal(now));
}
stack.peek().oper = ch;
priStack.push(nowPri);
}
++i;
}
while (stack.size() > 1) {
Expression now = stack.pop(), last = stack.pop();
stack.push(last.cal(now));
}
return stack.peek().toList();
}
}

  

Analysis:

Using stack to implement the arithmetic operation.

We can give each operator a priority number, + and - is 0, while * is 1. When an operator is inside "()", its priority increases by 2 for every "()".

For example:

4*(a-(b+(x*y))+d*e)

the operator priorities are:

*   -   +   *   +   *

1  2   3  7   2   3

always do the operation with highest priority first.

class Trem if for each single term in our final answer.

class Expression is a list of class Terms.

We can do +-* for two Expressions.

Reference:

https://leetcode.com/problems/basic-calculator-iv/discuss/113551/Java-solution-using-stack

770. Basic Calculator IV的更多相关文章

  1. [LeetCode] Basic Calculator IV 基本计算器之四

    Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {&q ...

  2. [Swift]LeetCode770. 基本计算器 IV | Basic Calculator IV

    Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {&q ...

  3. leetcode770. Basic Calculator IV

    此题真可谓是练习编程语言的绝好材料 ! import java.util.*; class Solution { class Item { Map<String, Integer> var ...

  4. 224. Basic Calculator + 227. Basic Calculator II

    ▶ 两个四则表达式运算的题目,第 770 题 Basic Calculator IV 带符号计算不会做 Orz,第 772 题 Basic Calculator III 要收费 Orz. ▶ 自己的全 ...

  5. [LeetCode] Basic Calculator 基本计算器

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  6. [LeetCode] Basic Calculator III 基本计算器之三

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  7. [LeetCode] 772. Basic Calculator III 基本计算器之三

    Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...

  8. [LeetCode] Basic Calculator II 基本计算器之二

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

  9. Basic Calculator II

    Implement a basic calculator to evaluate a simple expression string. The expression string contains ...

随机推荐

  1. IO密集型和计算密集型

    我们常说的多任务或者单任务分为两种: IO密集型的任务  计算密集型的任务   IO密集型的任务或:有阻塞的状态,就是不一直会运行CPU(中间就一个等待状态,就告诉CPU 等待状态,这个就叫IO密集型 ...

  2. Spring用了哪些设计模式

    单例:只产生一个对象,共享对象的资源: 多例:产生多个对象,对象资源没有联系:(action) 在ssm框架中 service层.dao层.controller层都是默认使用单例模式,只会产生唯一 一 ...

  3. JMeter处理返回结果unicode转码为中文

    问题举例: { "ServerCode":"200","ServerMsg":"\u6210\u529f"," ...

  4. PowerDesign生成数据库

    最近要忙期考,但还是决定每天抽点空来写CodeSmith的系列文章了,在此实在不敢用教程这个词语,毕竟自己对CodeSmith了解的也不是很多,有很多牛人都在博客园发布了不少关于CodeSmith的文 ...

  5. 高性能迷你React框架anujs1.1.0发布

    本版本对setState与forceUpdate内部依赖的setStateImpl进行了重构,性能稳定在60pfs之上.并且将组件实例的所有内部方法与属性都改成以___开头. https://gith ...

  6. vsCode关闭代码检查工具

    在script标签里,第一行输入下面的内容即可:

  7. (转)PWA(Progressive Web App)渐进式Web应用程序

    PWA 编辑 讨论 PWA(Progressive Web App)是一种理念,使用多种技术来增强web app的功能,可以让网站的体验变得更好,能够模拟一些原生功能,比如通知推送.在移动端利用标准化 ...

  8. MFC笔记3

    1. C6有默认的提示代码功能,但是其默认的快捷键是Ctrl + Space,这一般情况下是切换输入法快捷键,所以,只需重新设置一下快捷键就可以实现提示代码功能,具体设置位置如下: 工具(T) -&g ...

  9. 关于C语言头文件写法的探讨

    我不是软件工程出身,对于这方面一直处于探索阶段. 目前按照这样的习惯吧. 除主函数所在的文件以外,为每一个源文件配置一个头文件. 头文件里面不能写变量的申明和定义.头文件里面只写 #define,st ...

  10. DB2 公共表表达式(WITH语句的使用)

    ----start 说起WITH 语句,除了那些第一次听说WITH语句的人,大部分人都觉得它是用来做递归查询的.其实那只是它的一个用途而已,它的本名正如我们标题写的那样,叫做:公共表表达式(Commo ...