当前位置:网站首页>Graphical LeetCode - 640. Solving Equations (Difficulty: Moderate)
Graphical LeetCode - 640. Solving Equations (Difficulty: Moderate)
2022-08-11 03:35:00 【Java Muse】
一、题目
求解一个给定的方程,将 x 以字符串 "x=#value" 的形式返回.该方程仅包含 '+' , '-' 操作,变量 x 和其对应系数.
如果方程没有解,请返回 "No solution" .如果方程有无限解,则返回 “Infinite solutions” .
如果方程中只有一个解,要保证返回值 'x' 是一个整数.
二、示例
2.1> 示例 1:
【输入】 equation = "x+5-3+x=6+x-2"
【输出】 "x=2"
2.2> 示例 2:
【输入】 equation = "x=x"
【输出】 "Infinite solutions"
2.3> 示例 3:
【输入】 equation = "2x=x"
【输出】 "x=0"
提示:
3<= equation.length <=1000equation只有一个 '='.equation方程由整数组成,其绝对值在[0, 100]范围内,不含前导零和变量 'x' .
三、解题思路
3.1> 思路1:
根据题目描述,equation只有一个“=”,So we can first pass the entire string of equations throughsplit("=")split it into two parts:left side equation string&right side equation string.Why split the whole equation by the equal sign??其实有两个主要的原因,首先:We want to parse the equation string,then we can provide a general method of splitting equation strings,In this way, the equation strings on the left and right sides can be split by calling this method..下面我们以equation="x+5-3+x=6+x-2"为例:

split by equals“left side equation string”和“right side equation string”之后,我们就需要Analytic equation of the string了.Strings are generally composed of three types:首先,“加号”或“减号”;其次,x变量;最后,非xinteger number of.那么,when we analyze,就可以通过“加号”或者“减号”to separate operator and not operator.这里可以通过substring(...)和indexOf(...)method to get the substring.以字符串x+5-3+x为例,判断indexOf("-")或indexOf("+")的下标位置,取indexValues under the smallest as a split at the end,At the end of the splitindex=1,所以通过e.substring(0, 1)Obtain intercept string“x”.最后,我们的eis the remaining string after the interception.Continue to split according to the above logic,最终会将“x+5-3+x”拆分为:“x”,“+5”,“-3”,“+x”.具体操作如下所示:

At this time there is a need to pay attention to special situation,that is if the first one is negative,So let's deal with it specially,Because we are in the process of the operation of the above,是通过indexOf确定“加号”或“减号”的位置,And then the interception in front of the string,那么,如果我们通过indexOf("-")Available subscript for position0,Then the intercepted string is an empty string“”了.所以,我们要通过indexOf("-", 1)或者indexOf("+", 1)来进行判断,即:从下标为1的位置开始,instead of subscripting from0的位置开始判断.具体操作如下所示:

After we finish parsing the string equation,我们就把xVariables are placed to the left of the equals sign,将非xvariable to the right of the equals sign.那么,在运算过程中,如果xvariable on the right,then since it is going to be moved to the left,所以,Its positive becomes negative,And negative numbers become positive numbers.对于非xThe movement of variables will also follow this.Then after moving,我们会统计x的总和(xSum)以及非x数字的总和(sum).那么当xSum等于0并且sum等于0的时候,方法返回“Infinite solutions”;否则,如果只有xSum等于0,那么则返回“No solution”;否则,返回 x= sum/xSum.具体操作如下所示:

四、代码实现
4.1> 实现1:
class Solution {
int xSum = 0; // 所有x,are moved to the left of the equal sign for calculation
int sum = 0; // 所有数字,are moved to the right of the equal sign for calculation
public String solveEquation(String equation) {
calculate(equation.split("=")[0], true);
calculate(equation.split("=")[1], false);
return (xSum == 0 && sum == 0) ? "Infinite solutions" : (xSum == 0 ? "No solution" : "x=" + sum/xSum);
}
public void calculate(String equation, boolean left) {
while(true) {
if (equation == null || equation.equals("")) break;
// 防止第一个数是负数,将其当做减号,So start from the first comparison
int minusIndex = equation.indexOf("-", 1) == -1 ? Integer.MAX_VALUE : equation.indexOf("-", 1);
int plusIndex = equation.indexOf("+", 1) == -1 ? Integer.MAX_VALUE : equation.indexOf("+", 1);
int endIndex = (minusIndex == Integer.MAX_VALUE && plusIndex == Integer.MAX_VALUE) ? equation.length() : Math.min(minusIndex, plusIndex);
String numStr = equation.substring(0, endIndex);
if (numStr.contains("x")) {
// 针对x或者nx的特殊处理
int xnum = (numStr.equals("x") || numStr.equals("+x")) ? 1 : (numStr.equals("-x") ? -1: Integer.valueOf(numStr.replace("x", "")));
xSum += left ? xnum : -xnum;
} else { // 减法操作
sum += left ? -Integer.valueOf(numStr) : Integer.valueOf(numStr);
}
equation = equation.substring(endIndex);
}
}
}
今天的文章内容就这些了:
写作不易,笔者几个小时甚至数天完成的一篇文章,只愿换来您几秒钟的 点赞 & 分享 .
更多技术干货,欢迎大家关注公众号“爪哇缪斯” ~ \(^o^)/ ~ 「干货分享,每天更新」
边栏推荐
- How to rebuild after pathman_config and pathman_config_params are deleted?
- Leetcode 450. 删除二叉搜索树中的节点
- (Nips-2015) Spatial Transformer Network
- Paper Accuracy - 2017 CVPR "High-Resolution Image Inpainting using Multi-Scale Neural Patch Synthesis"
- Unity2D animation (1) introduction to Unity scheme - animation system composition and the function of use
- LeetCode Hot Questions (12. The Best Time to Buy and Sell Stocks)
- 构建程序化交易系统需要注意什么问题?
- [BX] and loop
- 【FPGA】day18-ds18b20实现温度采集
- Qnet弱网测试工具操作指南
猜你喜欢

UNI-APP_iphone苹果手机底部安全区域

Homework 8.10 TFTP protocol download function

Multi-merchant mall system function disassembly 26 lectures - platform-side distribution settings

The development of the massage chair control panel makes the massage chair simple and intelligent

Add user error useradd: cannot open /etc/passwd

Salesforce disbands the Chinese team, which CRM product is more suitable for the Chinese

【FPGA】day19-二进制转换为十进制(BCD码)

【Yugong Series】August 2022 Go Teaching Course 036-Type Assertion

MongoDB 基础了解(二)

常用认证机制
随机推荐
【FPGA】SDRAM
watch监听
QueryDet:级联稀疏query加速高分辨率下的小目标检测
Rotary array problem: how to realize the array "overall reverse, internal orderly"?"Three-step conversion method" wonderful array
The problem that Merge will be lost again after code Revert has been solved
【愚公系列】2022年08月 Go教学课程 036-类型断言
没想到MySQL还会问这些...
DNS separation resolution and intelligent resolution
云平台下ESB产品开发步骤说明
你不知道的 console.log 替代品
【愚公系列】2022年08月 Go教学课程 035-接口和继承和转换与空接口
VIT 源码详解
Design and Realization of Employment Management System in Colleges and Universities
输入起始位置,终止位置截取链表
元素的BFC属性
Element's BFC attribute
CSDN blog replacement skin
构建程序化交易系统需要注意什么问题?
【FPGA】day18-ds18b20实现温度采集
(Nips-2015) Spatial Transformer Network