Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- int evaluate(std::string& s) {
- int ans=0;
- bool plus=true;
- int ii=0;
- std::string::size_type sz;
- while(ii<s.length()) {
- if (s[ii]=='(' || s[ii]==')') {
- ++ii;
- continue;
- }
- if (s[ii]==' '){
- ++ii;
- continue;
- }
- if (s[ii]=='+'){
- if (s[ii+1]=='-') {
- plus=false;
- ii+=2;
- }
- else {
- plus=true;
- ++ii;
- }
- continue;
- }
- else if (s[ii]=='-') {
- if (s[ii+1]=='-') {
- plus=true;
- ii+=2;
- }
- else{
- plus=false;
- ++ii;
- }
- continue;
- }
- else {
- // we have digits here.. get the number..
- std::string num="";
- //std::cout<<int(s[ii])<<std::endl;
- while(s[ii]>=48 && s[ii]<=57) {
- //std::cout<<s[ii]<<std::endl;
- num+=s[ii];
- ++ii;
- }
- //digit constructed..
- int digi = std::stoi (num,&sz);
- if (plus)
- ans += digi;
- else
- ans -= digi;
- }
- }
- return ans;
- }
- public:
- int calculate(string s) {
- if (s.empty())
- return 0;
- std::stack<string> stk;
- for (int ii=0; ii<s.length(); ++ii) {
- if (s[ii]==')'){
- // Pop till '(' and create string and send and then push..
- std::string exp = "";
- while (!stk.empty() && stk.top()!="("){
- exp = stk.top()+exp;
- stk.pop();
- }
- stk.pop();
- stk.push(std::to_string(evaluate(exp)));
- }
- else {
- stk.push(std::string(1,s[ii]));
- }
- }
- std::string exp = "";
- while (!stk.empty() && stk.top()!="("){
- exp = stk.top()+exp;
- stk.pop();
- }
- return evaluate(exp);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement