770. Basic Calculator IV
Given an
expressionsuch asexpression = "e + 8 - a + 5"and an evaluation map such as{"e": 1}(given in terms ofevalvars = ["e"]andevalints = [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:
expressionwill have length in range[1, 250].evalvars, evalintswill 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的更多相关文章
- [LeetCode] Basic Calculator IV 基本计算器之四
Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {&q ...
- [Swift]LeetCode770. 基本计算器 IV | Basic Calculator IV
Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {&q ...
- leetcode770. Basic Calculator IV
此题真可谓是练习编程语言的绝好材料 ! import java.util.*; class Solution { class Item { Map<String, Integer> var ...
- 224. Basic Calculator + 227. Basic Calculator II
▶ 两个四则表达式运算的题目,第 770 题 Basic Calculator IV 带符号计算不会做 Orz,第 772 题 Basic Calculator III 要收费 Orz. ▶ 自己的全 ...
- [LeetCode] Basic Calculator 基本计算器
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [LeetCode] Basic Calculator III 基本计算器之三
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [LeetCode] 772. Basic Calculator III 基本计算器之三
Implement a basic calculator to evaluate a simple expression string. The expression string may conta ...
- [LeetCode] Basic Calculator II 基本计算器之二
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
- Basic Calculator II
Implement a basic calculator to evaluate a simple expression string. The expression string contains ...
随机推荐
- awk选取制定行数,条件判断等
awk '{if(NR%5==0){print}}' your_file 取出可以被5整除的数awk '{if(NR<=300){print}}' your_file 取出行数小于300的数据a ...
- python 对象转字典
从数据库中取出的数数据是 对象类型的,不能直接展示出来,需要转成字典类型,然后转成json 字符串,传给前端: data = {} data.update(obj.__dict__) print(da ...
- Rocket MQ 1 - 用
参考 http://www.iocoder.cn/categories/RocketMQ/ ; https://www.jianshu.com/nb/16219849 首先上启动方法,分别启动name ...
- C语言中 .h文件和.c文件的区别
要理解.c文件与.h文件有什么不同之处,首先需要弄明白编译器的工作过程,一般说来编译器会做以下几个过程: 1.预处理阶段 2.词法与语法分析阶段 3.编译阶段,首先编译成纯汇编语句,再将之汇编成跟CP ...
- Shapley值的一个应用
看书有这样一个问题,某互联网公司今天需要加班,需要编写一个500行的程序代码,产品经理找了三个程序员来完成.按照完成量发奖金:1号普通程序员独立能写100行,2号大神程序员独立能写125行,3号美女程 ...
- Zabbix告警脚本-短信
[root@iot-svndata02 bin]# cat zbsms.sh #!/bin/sh #curl http://221.179.180.137:8080/smsaServer/lkSend ...
- POJ-1797.HeavyTransportation(最长路中的最小权值)
本题思路:最短路变形,改变松弛方式即可,dist存的是源结点到当前结点的最长路的最小权值. 参考代码: #include <cstdio> #include <cstring> ...
- node.js中通过dgram数据报模块创建UDP服务器和客户端
node.js中 dgram 模块提供了udp数据包的socket实现,可以方便的创建udp服务器和客户端. 一.创建UDP服务器和客户端 服务端: const dgram = require('dg ...
- 搭建Fabric网络(三)artifacts是怎么生成的:cryptogen和configtxgen
在first-network里,./byfn.sh generate可以生成artifacts文件. generate参数其实是使用了cryptogen和configtxgen这两个工具,这两个工具分 ...
- 18. pt-pmp
pt-pmp 是一个非常简单的工具,可以用来获取MySQL的堆栈信息.工具首先获取运行过程中的mysqld堆栈信息,然后将相似的线程进行汇总排序,根据调用频繁程度从高到低打印出来. 查看pt-pmp的 ...