- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 44 lines of C++ from the credited upstream file 640.cpp.
- The implementation keeps its working state in language-native values and containers.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 string solveEquation(string equation) {4 const string lhsEquation = equation.substr(0, equation.find('='));5 const string rhsEquation = equation.substr(equation.find('=') + 1);6 const auto& [lhsCoefficient, lhsConstant] = calculate(lhsEquation);7 const auto& [rhsCoefficient, rhsConstant] = calculate(rhsEquation);8 const int coefficient = lhsCoefficient - rhsCoefficient;9 const int constant = rhsConstant - lhsConstant;10 11 if (coefficient == 0 && constant == 0)12 return "Infinite solutions";13 if (coefficient == 0 && constant != 0)14 return "No solution";15 return "x=" + to_string(constant / coefficient);16 }17 18 private:19 pair<int, int> calculate(const string& s) {20 int coefficient = 0;21 int constant = 0;22 int num = 0;23 int sign = 1;24 25 for (int i = 0; i < s.length(); ++i) {26 const char c = s[i];27 if (isdigit(c))28 num = num * 10 + (c - '0');29 else if (c == '+' || c == '-') {30 constant += sign * num;31 sign = c == '+' ? 1 : -1;32 num = 0;33 } else {34 if (i > 0 && num == 0 && s[i - 1] == '0')35 continue;36 coefficient += num == 0 ? sign : sign * num;37 num = 0;38 }39 }40 41 return {coefficient, constant + sign * num};42 }43};44