Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
solve-the-equation.cpp 1.71 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2017-07-20 23:53 +08:00 . update
// Time: O(n)
// Space: O(n)
class Solution {
public:
string solveEquation(string equation) {
auto a = 0, b = 0;
auto side = 1;
int submatches[] = { 1, 2, 3, 4 };
auto e = regex("(=)|([-+]?)(\\d*)(x?)");
for (regex_token_iterator<string::iterator> it(equation.begin(), equation.end(), e, submatches), end;
it != end;) {
auto eq = (it++)->str();
auto sign = (it++)->str();
auto num = (it++)->str();
auto isx = (it++)->str();
if (!eq.empty()) {
side = -1;
} else if (!isx.empty()) {
a += side * stoi(sign + "1") * stoi(num.empty() ? "1" : num);
} else if (!num.empty()) {
b -= side * stoi(sign + num);
}
}
return a != 0 ? "x=" + to_string(b / a) : b != 0 ? "No solution" : "Infinite solutions";
}
};
// Time: O(n)
// Space: O(n)
class Solution2 {
public:
string solveEquation(string equation) {
equation = regex_replace(equation, regex("(^|[+=-])x"), "$011x");
auto pos = equation.find('=');
auto l = coef(equation.substr(0, pos));
auto r = coef(equation.substr(pos + 1));
auto a = l.first - r.first;
auto b = r.second - l.second;
return a != 0 ? "x=" + to_string(b / a) : b != 0 ? "No solution" : "Infinite solutions";
}
private:
pair<int, int> coef(string s) {
auto a = 0, b = 0;
auto e = regex("(^|[+-])\\d+x?");
for (regex_token_iterator<string::iterator> it(s.begin(), s.end(), e), end;
it != end; ++it) {
(it->str().back() == 'x' ? a : b) += stoi(*it);
}
return {a, b};
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助