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]的更多相关文章

  1. 【LeetCode】640. Solve the Equation 解题报告(Python)

    [LeetCode]640. Solve the Equation 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: ht ...

  2. LC 640. Solve the Equation

    Solve a given equation and return the value of x in the form of string "x=#value". The equ ...

  3. 【leetcode】640. Solve the Equation

    题目如下: 解题思路:本题的思路就是解析字符串,然后是小学时候学的解方程的思想,以"2x+3x-6x+1=x+2",先把左右两边的x项和非x项进行合并,得到"-x+1=x ...

  4. 640. Solve the Equation

    class Solution { public: string solveEquation(string equation) { int idx = equation.find('='); , v1 ...

  5. 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 ...

  6. hdu 2199 Can you solve this equation?(二分搜索)

    Can you solve this equation? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K ( ...

  7. hdu 2199:Can you solve this equation?(二分搜索)

    Can you solve this equation? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K ( ...

  8. 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 ...

  9. HDU 2199 Can you solve this equation? (二分 水题)

    Can you solve this equation? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K ( ...

  10. hdoj 2199 Can you solve this equation?【浮点型数据二分】

    Can you solve this equation? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K ( ...

随机推荐

  1. 配置web项目session永不超时

    众所周知,当用户登录网站后较长一段时间没有与服务器进行交互,将会导致服务器上的用户会话数据(即session)被销毁.此时,当用户再次操作网页时,如果服务器进行了session校验,那么浏览器将会提醒 ...

  2. Oracle之视图

    Oracle之视图 2018.9.12 由于视图的数据与表数据互相关联,所以切记谨慎操作 建立视图 使用下面sql语句来完成视图的创建 create or replace view 视图名 as se ...

  3. he lover you 用python 搞为 eh revol uoy 。

    1.字符串序列翻转  ----   字符串切片 a_str = “abc”[::-1] 2.字符串分割: b_str  = ‘ ds fdf  ds ’ b_str .split(" 空格& ...

  4. TCP协议与UDP协议

    网络通信协议规定了网络通信时,数据必须采用的格式.常见的协议有TCP协议,UDP协议. TCP协议 :(Transmission Control Protocol)传输控制协议. TCP是一种面向连接 ...

  5. EF core Code First 简单的使用方法

    好吧,我又回来了,其实一直都想写一篇关于EF core 的文章去记录自己在开发时候遇到的问题. 为什么要使用EF框架呢,因为原始的ADO.NET需要编写大量的数据访问代码,所以使用EF会更方便.但是今 ...

  6. Mybatis中多个参数的问题&&动态SQL&&查询结果与类的对应

    ### 1. 抽象方法中多个参数的问题 在使用MyBatis时,接口中的抽象方法只允许有1个参数,如果有多个参数,例如: Integer updatePassword( Integer id, Str ...

  7. numpy的总结

    一:基础篇 1)数值 import numpy as np np.set_printoptions(linewidth=200,suppress=True) a = np.array([1,2,3,4 ...

  8. kali linux 安装谷歌浏览器

    kali linux 版本 2018.2 先下载谷歌浏览器安装包 wget https://dl.google.com/linux/direct/google-chrome-stable_curren ...

  9. 阅读《大型网站技术架构》,并结合"重大需求征集系统"有感

    今天阅读了<大型网站技术架构:核心原理与案例分析>的第五.六.七章.这三张主要是讲述了一个系统的可用性.伸缩性和可扩展性.而根据文中所讲述的,一个系统的可用性主要是体现在这个系统的系统服务 ...

  10. 2.1 进程控制之fork创建子进程

    fork()函数 目标:熟悉fork创建一个和多个子进程子线程 函数原型:pid_t fork(void); 返回值:成功返回:① 父进程返回子进程的ID(非负) ②子进程返回 0 : 失败返回-1. ...