Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
62 lines (59 loc) · 1.89 KB

File metadata and controls

62 lines (59 loc) · 1.89 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package leetcode;
import java.util.ArrayList;
import java.util.List;
public class leetcode640 {
public String solveEquation(String equation) {
String []lr=equation.split("=");
int lhs=0,rhs=0;// lhs代表左侧x的系数,rhs代表右侧整数
for (String x:
breakIt(lr[0])) {
if (x.indexOf("x")>=0){ //如果式子是nx
lhs+=Integer.parseInt(coeff(x));
}else{
rhs-=Integer.parseInt(x);
}
}
for (String x:
breakIt(lr[1])) {
if (x.indexOf("x")>=0){ //如果式子是nx
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 String coeff(String x) {
if (x.length()>1&&x.charAt(x.length()-2)>='0'&&x.charAt(x.length()-2)<='9'){
//x.charAt(x.length()-2)>'0'&&x.charAt(x.length()-2)<'9' 是为了处理+x/-x的意外情况
return x.replace("x","");
}
return x.replace("x","1");
}
// 拆解字符串
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;
}
public static void main(String[] args) {
new leetcode640().solveEquation("99x=99");
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.