[LeetCode] 640. Solve the Equation

Problem

Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and 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"

Note

这破题只有一个考点:正则表达式

Solution

class Solution {
    public String solveEquation(String equation) {
        String[] sides = equation.split("=");
        String left = sides[0], right = sides[1];
        int[] ls = getCounts(left);
        int[] rs = getCounts(right);
        int countX = ls[0]-rs[0];
        int countNum = rs[1]-ls[1];
        if (countX == 0) {
            if (countNum == 0) return "Infinite solutions";
            else return "No solution";
        }
        
        int x = countNum/countX;
        StringBuilder sb = new StringBuilder();
        sb.append("x=").append(x);
        return sb.toString();
    }
    private int[] getCounts(String str) {
        int[] res = new int[2];
        String[] parts = str.split("(?=[+-])"); //this is what this problem is
        for (String part: parts) {
            if (part.equals("x") || part.equals("+x")) res[0]++;
            else if (part.equals("-x")) res[0]--;
            else if (part.contains("x")) res[0] += Integer.valueOf(part.substring(0, part.indexOf("x")));
            else res[1] += Integer.valueOf(part);
        }
        return res;
    }
}

你可能感兴趣的:(regexp,string,math,java)