LeetCode #640 Solve the Equation 求解方程 640 Solve the Equation 求解方程

640 Solve the Equation 求解方程

Description:
Solve a given equation and return the value of 'x' in the form of a string "x=#value". The equation contains only '+', '-' operation, the variable 'x' and its coefficient. You should return "No solution" if there is no solution for the equation, or "Infinite solutions" if there are infinite solutions for the equation.

If there is exactly one solution for the equation, we ensure that the value of 'x' is an integer.

Example:

Example 1:

Input: equation = "x+5-3+x=6+x-2"
Output: "x=2"

Example 2:

Input: equation = "x=x"
Output: "Infinite solutions"

Example 3:

Input: equation = "2x=x"
Output: "x=0"

Example 4:

Input: equation = "2x+3x-6x=x+2"
Output: "x=-1"

Example 5:

Input: equation = "x=x+2"
Output: "No solution"

Constraints:

3 <= equation.length <= 1000
equation has exactly one '='.
equation consists of integers with an absolute value in the range [0, 100] without any leading zeros, and the variable 'x'.

題目描述:
求解一個給定的方程,將x以字符串"x=#value"的形式返回。該方程僅包含'+',' - '操作,變量 x 和其對應係數。

如果方程沒有解,請返回“No solution”。

如果方程有無限解,則返回“Infinite solutions”。

如果方程中只有一個解,要保證返回值 x 是一個整數。

示例 :

示例 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', '-x' 替換爲 '+1x', '-1x' 方便後續處理
按照 '=' 分別求 ax = b 中的 a 和 b, 注意正負號即可
最後按 a != 0, b == 0 和其他討論方程的解
時間複雜度 O(n), 空間複雜度 O(n)

代碼:
C++:

class Solution 
{
private:
    pair<int, int> calculate(string str)
    {
        int a = 0, b = 0, sign = 1;
        if (str[0] != '+' and str[0] != '-') str = '+' + str;
        int n = str.size();
        for (int i = 0; i < n; i++)
        {
            if (str[i] == '+') sign = 1;
            else if (str[i] == '-') sign = -1;
            else if (str[i] == 'x')
            {
                if (sign == 1) ++a;
                else --a;
            }
            else
            {
                int j = i;
                int t = 0;
                while (j < n and isdigit(str[j])) t = t * 10 + (str[j++] - '0');
                t = sign * t;
                if (str[j] == 'x')
                {
                    a += t;
                    i = j;
                }
                else
                {
                    b += t;
                    i = j - 1;
                }
            }
        }
        return {a, b};
    }
public:
    string solveEquation(string equation) 
    {
        int equal = equation.find('=');
        string left = equation.substr(0, equal), right = equation.substr(equal + 1);
        auto left_pair = calculate(left), right_pair = calculate(right);
        int a = left_pair.first - right_pair.first, b =  right_pair.second - left_pair.second;
        if (a) return "x=" + to_string(b / a);
        else if (!b) return "Infinite solutions";
        return "No solution";
    }
};

Java:

class Solution {
    public String solveEquation(String equation) {
        int a = 0, b = 0, sign = 1;
        for (String f: equation.split("=")) {
            f = f.replace("-", "+-");
            for (String num: f.split("\\+")) {
                if (num.isEmpty()) continue;
                if (num.contains("x")) {
                    if (num.length() == 1) a += sign;
                    else if (num.length() == 2 && num.charAt(0) == '-') a += -sign;
                    else a += sign * Integer.parseInt(num.substring(0, num.length() - 1));
                }
                else b -= sign * Integer.parseInt(num);
            }
            sign = -1;
        }
        if (a != 0) return "x=" + b / a;
        else if (b == 0) return "Infinite solutions";
        return "No solution";
    }
}

Python:

class Solution:
    def solveEquation(self, equation: str) -> str:
        e = equation.replace('-x', '-1x').replace('-', '+-')
        a = b = 0
        for i, f in enumerate(e.split('=')):
            if f[0] != '+':
                f = '+' + f
            f = f.replace('+x', '+1x')
            for t in f.split('+'):
                if not t:
                    continue
                if 'x' in t:
                    a += (1 - 2 * i) * int(t[:len(t) - 1])
                else:
                    b -= (1 - 2 * i) * int(t)
        if a:
            return 'x=' + str(b // a)
        elif not b:
            return 'Infinite solutions'
        return 'No solution'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章