leetcode 640. Solve the Equation 等式计算 + C++stringstream的一个很好地示范
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”
本题题意很简单,就是直接分析即可,注意使用C++的stringstream来处理,就是有点烦,别的都很简单
建议和leetcode 609. Find Duplicate File in System C++stringstream的一个很好地示范 一起学习
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
#include <iomanip>
using namespace std;
class Solution
{
public:
string solveEquation(string equation)
{
int index = equation.find('=');
vector<int> left = getRes(equation.substr(0, index));
vector<int> right = getRes(equation.substr(index + 1));
int x = left[0] - right[0];
int num = right[1] - left[1];
string res = "";
if (x == 0 && num == 0)
res = "Infinite solutions";
else if (x == 0 && num != 0)
res = "No solution";
else
res = "x=" + to_string(num / x);
return res;
}
vector<int> getRes(string eq)
{
vector<int> res;
stringstream ss(eq);
char c;
int num = 0, x = 0, tmp;
string a = "";
for (int i = 0; i <= eq.length(); i++)
{
if (i<eq.length())
ss >> c;
if (c == '+' || c == '-' || i == eq.length())
{
if (a.size() >= 1)
{
if (a.back() == 'x')
{
if (a == "x" || a == "+x")
tmp = 1;
else if (a == "-x")
tmp = -1;
else
tmp = stoi(a.substr(0, a.length() - 1));
x += tmp;
}
else
{
tmp = stoi(a);
num += tmp;
}
}
if (c == '-')
a = "-";
else
a = "";
}
else
a += c;
}
res = { x,num };
return res;
}
};
还没有评论,来说两句吧...