[LeetCode]640解方程式
问题描述:
示例 1: 输入: "x+5-3+x=6+x-2" 输出: "x=2" 示例 2: 输入: "x=x" 输出: "Infinite solutions" 示例 3: 输入: "2x=x" 输出: "x=0" 示例 4: 输入: "2x+3x-6x=x+2" 输出: "x=-1" 示例 5: 输入: "x=x+2" 输出: "No solution"
思路:考的是字符串的解析
跟平时学的解方程的一样,根据等号将方程分为两个部分
将两端的方程的X的系数和,和常数和计算出来,然后两边的X的系数和相减,常数和相减,相除,分清楚情况就行
解析字符串注意边界
public class Main { public static void main(String[] args) { System.out.println(solveEquation("x+5-3+x=6+x-2")); } public static String solveEquation(String equation) { //等号为界,分为两边 String[] split = equation.split("="); int[] left = findPreNumSum(split[0]); int[] right = findPreNumSum(split[1]); if (left[0]==right[0]&&left[1]==right[1]) return "Infinite solutions"; else if (left[0]==right[0]&&left[1]!=right[1]){ return "No solution"; }else { return "x="+(right[1]-left[1])/(left[0]-right[0]); } } public static int[] findPreNumSum(String s){ int x_sum = 0; int integerSum = 0; int length = s.length(); for (int i = 0;i < length;i++){ char it = s.charAt(i); char pre = i>0?s.charAt(i-1):'n'; char next = i>length-2?'n':s.charAt(i+1); if(it=='+'||it=='-') continue; //此分支计算等号某一侧的x的系数和 if (it == 'x'||it=='X'){ if (pre=='n'){ //x位于第一位 x_sum = x_sum + 1; }else { int count = 1; int sum = 0; int j; for (j = i-1;;){ //从当前遍历位(即x)的前一位往前推 if(j<0||s.charAt(j)=='+'||s.charAt(j)=='-'){ if (i-j==1&&(s.charAt(j)=='+'||s.charAt(j)=='-')){ //非第一位的x系数为1/-1的情况 x_sum = x_sum + (s.charAt(j)=='+'?1:(-1)); System.out.println(x_sum); } //x系数累乘的倍数归为1 count = 1; break; } //算系数,不分加减 sum = sum + (s.charAt(j)-'0')*count; count = count * 10; j--; } //根据前面的符号来计算已遍历的x的系数和 x_sum = x_sum + ((j==-1||s.charAt(j)=='+')?1:(-1))*sum; count = 1; sum = 0; } } //此分支计算等号某一侧的常数和 else { //若此时遍历不是邻近x的数字,跳过 if (('0'<=next&&next<='9')||next=='x') continue; int count = 1; int sum = 0; int j; //从当前遍历位往前推,即算上本身 for (j = i;;){ if(j<0||s.charAt(j)=='+'||s.charAt(j)=='-'){ count = 1; break; } //同上,计算系数,不分符号 sum = sum + (s.charAt(j)-'0')*count; count = count * 10; j--; } //带上符号算已遍历的常数的和 integerSum = integerSum + ((j==-1||s.charAt(j)=='+')?1:(-1))*sum; count = 1; sum = 0; } } System.out.println(x_sum+"-"+integerSum); //返回此侧的x的系数和和常数和 return new int[]{x_sum,integerSum}; } }
太菜了,各位有更牛逼的解决办法告诉一下我呀