[leetcode-640-Solve the Equation]
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable xand its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If there is exactly one solution for the equation, we ensure that the value of x is an integer.
Example 1:
Input: "x+5-3+x=6+x-2"
Output: "x=2"
Example 2:
Input: "x=x"
Output: "Infinite solutions"
Example 3:
Input: "2x=x"
Output: "x=0"
Example 4:
Input: "2x+3x-6x=x+2"
Output: "x=-1"
Example 5:
Input: "x=x+2"
Output: "No solution"
Approach #1 Partioning Coefficients [Accepted]
In the current approach, we start by splitting the given equationequation based on = sign. This way, we've separated the left and right hand side of this equation. Once this is done, we need to extract the individual elements(i.e. x's and the numbers) from both sides of the equation. To do so, we make use of breakItfunction, in which we traverse over the given equation(either left hand side or right hand side), and put the separated parts into an array.
Now, the idea is as follows. We treat the given equation as if we're bringing all the x's on the left hand side and all the rest of the numbers on the right hand side as done below for an example.
x+5-3+x=6+x-2
x+x-x=6-2-5+3
Thus, every x in the left hand side of the given equation is treated as positive, while that on the right hand side is treated as negative, in the current implementation. Likewise, every number on the left hand side is treated as negative, while that on the right hand side is treated as positive. Thus, by doing so, we obtain all the x's in the new lhslhs and all the numbers in the new rhsrhs of the original equation.
Further, in case of an x, we also need to find its corresponding coefficients in order to evaluate the final effective coefficient of x on the left hand side. We also evaluate the final effective number on the right hand side as well.
Now, in case of a unique solution, the ratio of the effective rhsrhs and lhslhs gives the required result. In case of infinite solutions, both the effective lhslhs and rhsrhsturns out to be zero e.g. x+1=x+1. In case of no solution, the coefficient of x(lhslhs) turns out to be zero, but the effective number on the rhsrhs is non-zero.
Java
public class Solution {
public String coeff(String x) {
if (x.length() > 1 && x.charAt(x.length() - 2) >= '0' && x.charAt(x.length() - 2) <= '9')
return x.replace("x", "");
return x.replace("x", "1");
}
public String solveEquation(String equation) {
String[] lr = equation.split("=");
int lhs = 0, rhs = 0;
for (String x: breakIt(lr[0])) {
if (x.indexOf("x") >= 0) {
lhs += Integer.parseInt(coeff(x));
} else
rhs -= Integer.parseInt(x);
}
for (String x: breakIt(lr[1])) {
if (x.indexOf("x") >= 0)
lhs -= Integer.parseInt(coeff(x));
else
rhs += Integer.parseInt(x);
}
if (lhs == 0) {
if (rhs == 0)
return "Infinite solutions";
else
return "No solution";
}
return "x=" + rhs / lhs;
}
public List < String > breakIt(String s) {
List < String > res = new ArrayList < > ();
String r = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '+' || s.charAt(i) == '-') {
if (r.length() > 0)
res.add(r);
r = "" + s.charAt(i);
} else
r += s.charAt(i);
}
res.add(r);
return res;
}
}
Complexity Analysis
Time complexity : O(n)O(n). Generating cofficients and findinn $lhsandandrhswill takewilltakeO(n)$$.
Space complexity : O(n)O(n). ArrayList resres size can grow upto nn.
参考:
https://leetcode.com/articles/solve-the-equation/
[leetcode-640-Solve the Equation]的更多相关文章
- 【LeetCode】640. Solve the Equation 解题报告(Python)
[LeetCode]640. Solve the Equation 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: ht ...
- LC 640. Solve the Equation
Solve a given equation and return the value of x in the form of string "x=#value". The equ ...
- 【leetcode】640. Solve the Equation
题目如下: 解题思路:本题的思路就是解析字符串,然后是小学时候学的解方程的思想,以"2x+3x-6x+1=x+2",先把左右两边的x项和非x项进行合并,得到"-x+1=x ...
- 640. Solve the Equation
class Solution { public: string solveEquation(string equation) { int idx = equation.find('='); , v1 ...
- ACM:HDU 2199 Can you solve this equation? 解题报告 -二分、三分
Can you solve this equation? Time Limit: / MS (Java/Others) Memory Limit: / K (Java/Others) Total Su ...
- hdu 2199 Can you solve this equation?(二分搜索)
Can you solve this equation? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K ( ...
- hdu 2199:Can you solve this equation?(二分搜索)
Can you solve this equation? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K ( ...
- hdu 2199 Can you solve this equation?(高精度二分)
http://acm.hdu.edu.cn/howproblem.php?pid=2199 Can you solve this equation? Time Limit: 2000/1000 MS ...
- HDU 2199 Can you solve this equation? (二分 水题)
Can you solve this equation? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K ( ...
- hdoj 2199 Can you solve this equation?【浮点型数据二分】
Can you solve this equation? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K ( ...
随机推荐
- 解决:fontawesome-webfont.woff2?v=4.6.3 404 (Not Found)
用Bootstrap里面的字体,你项目中会报一个错,一个字体找不到,但我们的项目中却是存在这个字体的. 解决方法: 修改我们的Web.Config文件
- Python中使用list和tuple
list: Python内置的一种数据类型是列表:list.list是一种有序的集合,可以随时添加和删除其中的元素. 比如,列出班里所有同学的名字,就可以用一个list表示: 变量classmates ...
- python tips(持续更新中)
python tips 可变对象与不可变对象 在python中,可变对象有数值类型(int,float),字符串(str),元组(tuple),可变对象有列表(list),字典(dict),集合(se ...
- 删除Navicat在注册表信息
@echo offecho 正在删除navicat注册表REG DELETE HKEY_CURRENT_USER\Software\PremiumSoft\Data /fREG DELETE HKEY ...
- Flask—01-轻松入门Flask
Flask入门 WEB工作原理 C/S与B/S架构:客户端-服务器,浏览器-服务器 B/S架构工作原理 客户端(浏览器) <=> WEB服务器(nginx) <=> WSGI( ...
- SSM项目中用ajax尝试实现controller请求中重定向不起作用的问题
首先我在controller中有一个添加数据的方法: @RequestMapping(value="/emp",method=RequestMethod.POST) public ...
- linux系统下病毒排除思路
1.top查看是否有特别吃cpu和内存的进程,病毒进程kill是杀不死的,因为ps命令被修改 2.ls -la /proc/病毒进程pid/ pwd为病毒进程程序目录 一般在/usr/bin下 3. ...
- conda 安装 graph-tool, 无需编译
1. 添加以下channels到~/.condarc $ conda config --add channels conda-forge $ conda config --add channels o ...
- jquery把数组中年月相同的数组重新组成新的数组
//原数组var data = { results: [{ id:0, date:'2017-12-12', content:'123' },{ id:0, date:'2017-12-12', co ...
- Win7下如何安装python pygame的whl包
看了小甲鱼的python教程,对那个python版本的打飞机游戏很感兴趣,尝试运行,居然报错了,提示缺少pygame包: 仔细一看需要安装一个pygame的包,默认安装好python是不包括这个包的, ...