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. 18.Shiro与Springboot整合下登陆验证UserService未注入的问题

    Shiro与Springboot整合下登陆验证UserService未注入的问题 前言: 刚开始整合的情况下,UserService一执行,就会报空指针异常. 看了网上各位大神的讲解,什么不能用ser ...

  2. 协议类接口 - UART

    一.何为协议类接口? 双方约定信号的协议和满足时序要求. 二.UART如何传数据 通用异步收发器简称 UART,即“Universal Asynchronous Receiver Transmitte ...

  3. 优雅的QSignleton (四) 通过属性器实现MonoSingleton

      大家都出去过周六了,而我却在家写代码T.T...   接下来介绍通过属性器实现MonoSingleton. 代码如下: MonoSingletonProperty.cs namespace QFr ...

  4. SpringBoot学习16:springboot整合junit单元测试

    1.创建maven项目,修改pom.xml文件 <!--springboot项目依赖的父项目--> <parent> <groupId>org.springfram ...

  5. vue 父子组件相互传值

    子传父 逻辑: 单击子组件的按钮 ,触发它的单击事件   通过 $emit 触发父级自定义事件 并传一个值给父级 <div id="id"> <h3>儿子 ...

  6. windows10安装mysql8.0.11(免安装版)

    1.MySQL8.0.11下载网址:https://dev.mysql.com/downloads/mysql/ 2.配置环境变量:我的电脑->属性->高级系统设置->环境变量-&g ...

  7. js onsubmit和return false的关系

    一直以来,我都是以为onsubmit=“return false”就不会进行提交,但经过项目之后才知道return false只是避免了之后的跳转,但onsubmit已经是正在进行了,故onsubmi ...

  8. ELK的简述安装

    一.ElasticSearch集群的安装及其配置 https://www.cnblogs.com/gentle-awen/p/10000801.html 可视化x-pack安装: https://ww ...

  9. 一些斗鱼TV Web API [Some DouyuTv API]

    一些斗鱼TV Web API [Some DouyuTv API]   写在最前 去年TI5前开发了dotaonly.com,网站需要用到各个直播平台API.不像国外网站Twitch那样开放,都有现成 ...

  10. js bom和dom

    一, 前言 到目前为止,我们已经学过了JavaScript的一些简单的语法.但是这些简单的语法,并没有和浏览器有任何交互. 也就是我们还不能制作一些我们经常看到的网页的一些交互,我们需要继续学习BOM ...