1. Recursive String Replacement (Inner Parentheses First)
Intuition
Scan the string for the innermost matching pair of parentheses (...). Extract the substring and evaluate using standard basic calculator without parentheses. Replace the (...) slice with the computed string value. Repeat until no parentheses remain, then evaluate the remaining flat expression.
When to apply: Useful as a conceptual baseline or small prototype when string length is small (N <= 100).
Algorithm
- While string contains
(, find the first closing)and locate its matching open(. - Extract the inner substring without parentheses.
- Evaluate the flat expression using linear operator scanning.
- Replace the parenthesized segment in the original string with the computed number.
- Evaluate the final flat string and return result.
#include <iostream>#include <string>#include <vector>#include <cctype> using namespace std; class Solution { int evalFlat(string s) { vector<int> st; char sign = '+'; int num = 0; int n = s.length(); for (int i = 0; i < n; i++) { char c = s[i]; if (isdigit(c)) num = num * 10 + (c - '0'); if (i == n - 1 || (!isdigit(c) && c != ' ')) { if (sign == '+') st.push_back(num); else if (sign == '-') st.push_back(-num); else if (sign == '*') { int t = st.back(); st.pop_back(); st.push_back(t * num); } else if (sign == '/') { int t = st.back(); st.pop_back(); st.push_back(t / num); } sign = c; num = 0; } } int sum = 0; for (int v : st) sum += v; return sum; }public: int calculate(string s) { while (s.find('(') != string::npos) { int closeIdx = s.find(')'); int openIdx = s.rfind('(', closeIdx); string inner = s.substr(openIdx + 1, closeIdx - openIdx - 1); int val = evalFlat(inner); s = s.substr(0, openIdx) + to_string(val) + s.substr(closeIdx + 1); } return evalFlat(s); }}; int main() { Solution sol; cout << sol.calculate("2*(5+5*2)/3+(6/2+8)") << endl; return 0;}Time & Space Complexity
- Time complexity:
O(N^2)— String slicing and concatenation take O(N) per parenthesis level, leading to quadratic worst-case time for deeply nested expressions. - Space complexity:
O(N^2)— Repeated intermediate string copies allocate O(N2) total memory across reductions.