My first try is DFS by intuition, but it ended up with MLE. So, the expected solution are to use stack:
classSolution {structNode {node (int_V): V (_v), Isnum (true) {} Node (Charb): Brack (b), Isnum (false){} BOOLIsnum; intv; CharBrack; }; Public: voidEval (vector<node> &operands, vector<Char> &OPS) { while(Operands.size () >1&& operands.back (). Isnum && operands[operands.size ()-2].isnum&& ops.size () >0) { Charc =Ops.back (); Ops.pop_back (); intV0 =Operands.back (). V; Operands.pop_back (); intV1 =Operands.back (). V; Operands.pop_back (); intret; if(c = ='+') ret = v1 +V0; if(c = ='-') ret = v1-V0; Operands.push_back (ret); } } intCalculatestrings) {stringSS; for(auto c:s)if(c! =' ') SS + =C; Vector<Node>operands; Vector<Char>ops; size_t Len=ss.length (); inti =0; intoperand =0; while(I <Len) { Charc =Ss[i]; if(IsDigit (c)) {operand*=Ten; Operand+ = C-'0'; if(((i +1) < Len &&!isdigit (ss[i +1])) ||(i+1) ==Len) {operands.push_back (operand); Eval (operands, OPS); Operand=0; } } Else if(c = ='+'|| c = ='-') {ops.push_back (c); } Else if(c = ='(') {operands.push_back (Node ('(')); } Else if(c = =')') { intv =Operands.back (). V; Operands.pop_back (); Charb =operands.back (). Brack; Operands.pop_back (); Operands.push_back (v); Eval (operands, OPS); } I++; } returnoperands[0].v; }};
Leetcode "Basic Calculator"