- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 52 lines of C++ from the credited upstream file 1597.cpp.
- The implementation keeps its working state in language-native values and containers.
- 4 loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
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 Node* expTree(string s) {4 stack<Node*> nodes;5 stack<char> ops; 6 7 for (const char c : s)8 if (isdigit(c)) {9 nodes.push(new Node(c));10 } else if (c == '(') {11 ops.push(c);12 } else if (c == ')') {13 while (ops.top() != '(')14 nodes.push(buildNode(pop(ops), pop(nodes), pop(nodes)));15 ops.pop(); 16 } else if (c == '+' || c == '-' || c == '*' || c == '/') {17 while (!ops.empty() && compare(ops.top(), c))18 nodes.push(buildNode(pop(ops), pop(nodes), pop(nodes)));19 ops.push(c);20 }21 22 while (!ops.empty())23 nodes.push(buildNode(pop(ops), pop(nodes), pop(nodes)));24 25 return nodes.top();26 }27 28 private:29 Node* buildNode(char op, Node* right, Node* left) {30 return new Node(op, left, right);31 }32 33 34 bool compare(char op1, char op2) {35 if (op1 == '(' || op1 == ')')36 return false;37 return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-';38 }39 40 char pop(stack<char>& ops) {41 const char op = ops.top();42 ops.pop();43 return op;44 }45 46 Node* pop(stack<Node*>& nodes) {47 Node* node = nodes.top();48 nodes.pop();49 return node;50 }51};52