1. Description of the problem
Gives an expression of the genetic string type that evaluates the value of an expression. The expression contains only + 、-、 *,/, and spaces.
2. Methods and Ideas
This problem is similar to basic Calculator I, except that the left and right brackets are replaced with the multiplication symbol. The basic practice is to first turn to the form of a suffix expression and then perform the calculation.
Suffix expressions are vector<long> postfix
stored in the structure, for convenience, operators and operands are stored in the postfix vector, in order to differentiate, the operands are in the form of negative numbers, and when the calculation becomes a positive number.
classSolution { Public: vector<long>Convert2postfix (Const string&s) { Stack<char>Op vector<long>PostfixintTMP =0, Isprenum =0; for(inti =0; I < s.length (); i++) {Switch(S[i]) { Case "':Continue; Case ' * ': Case '/': while(!op.empty () && (op.top () = =' * '|| Op.top () = ='/') {Postfix.push_back (Op.top ()); Op.pop (); } op.push (S[i]); Break; Case ' + ': Case '-': while(!op.empty ()) {Postfix.push_back (Op.top ()); Op.pop (); } op.push (S[i]); Break;default:if(isprenum) tmp = tmp*Ten+ S[i]-' 0 ';Else{tmp = S[i]-' 0 '; Isprenum =1; }if(i+1==s.length () | | (I < S.length () && (s[i+1] >' 9 '|| s[i+1] <' 0 ')) {postfix.push_back (-tmp); Isprenum =0; } } } while(!op.empty ()) {Postfix.push_back (Op.top ()); Op.pop (); }returnPostfix }intCalculatestrings) { vector<long>Postfix = Convert2postfix (s);if(postfix.size () = =0)return 0; Stack<long>StLongb; for(inti =0; I < postfix.size (); i++) {Switch(Postfix[i]) { Case ' + ': a = St.top (); St.pop (); b = St.top (); St.pop (); St.push (B+a); Break; Case '-': a = St.top (); St.pop (); b = St.top (); St.pop (); St.push (B-A); Break; Case ' * ': a = St.top (); St.pop (); b = St.top (); St.pop (); St.push (b*a); Break; Case '/': a = St.top (); St.pop (); b = St.top (); St.pop ();if(A = =0)return 0; St.push (b/a); Break;default: St.push (-postfix[i]); } }returnSt.top (); }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode 227 Basic Calculator II