Topic Connection
https://leetcode.com/problems/basic-calculator/
Basic calculatordescription
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open (and closing parentheses), the Plus + or minus sign-, non-negative integers and Empty spaces.
Assume that the given expression was always valid.
Some Examples:
"1 + 1 = 2"
"2-1 + 2" = 3
"(1+ (4+5+2)-3) + (6+8)" = 23
Note: Do not use the Eval built-in library function.
Expression evaluation:
Class Expcalc {private:string ret;stack<char> op;stack<int> num;inline void Erase () {ret = ""; while (!op.empt Y ()) Op.pop (), while (!num.empty ()) Num.pop ();} inline int calc (int d1, int d2, char ch) {int val = 0;switch (ch) {case ' + ': val = d1 + d2;break;case '-': val = d2-d1;b Reak;} return Val;} Public:expcalc () {erase ();} ~expcalc () {erase ();} inline void Infixtopostfix (const string src) {int n = src.length (); for (int i = 0; i < n;) {if (' = = Src[i] | | ' = ' = = Src[i]) {i++; continue;} if (' (' = = = = Src[i]) Op.push (src[i++]), if (') ' = = Src[i]) {while (Op.top ()! = ' (') {ret + = Op.top (); ret + = "; Op.pop ();} Op.pop (); i++;} else if ('-' = = Src[i] | | ' + ' = = Src[i]) {while (!op.empty () && ('-' = = Op.top () | | ' + ' = = Op.top ()) {ret + = Op.top (); ret + = '; Op.pop ();} Op.push (src[i++]);} else {while (IsDigit (Src[i])) {ret + = src[i++];} RET + = ";}} while (!op.empty ()) {ret + = Op.top (); ret + = '; Op.pop ();} RET + = ' = ';} inline int Postfixcalc () {int n = ret.length (); for (int i = 0; i < n;) {if (' = = Ret[i] | | ' = ' = = Ret[i]) {i++; continue;} if ('-' = = Ret[i] | | ' + ' = = Ret[i]) {int d1 = Num.top (); Num.pop (); int d2 = Num.top (); Num.pop (); Num.push (Calc (d1, D2, ret[i++]));} else if (is Digit (Ret[i])) {int x = 0;while (IsDigit (Ret[i])) {x = x * + ret[i++]-' 0 ';} Num.push (x);}} return Num.top ();}}; Class Solution {Public:int calculate (string s) {if (S.empty ()) return 0;calc = new Expcalc;calc->infixtopostfix (s); int ans = Calc->postfixcalc (); return ans;} Private:expcalc *calc;};
Leetcode Basic Calculator