LeetCode() Basic Calculator不知道哪里错了

it2022-07-04  132

class Solution {public:    int calculate(string s) {        stack<int> num;        stack<char> symbol;        for(int i=0;i<s.length();i++){            if(s[i]==' ')   continue;            else if(s[i]=='('||s[i]=='+'||s[i]=='-')  symbol.push(s[i]);            else if(s[i]>='0'&&s[i]<='9'){                for(int j=i+1;j<s.length();j++){                    if(s[j]<'0'||s[j]>'9'){                        num.push(stoi(s.substr(i,j-i)));                        i=j-1;                        break;                    }                                        }            }            else if(s[i]==')'){                stack<int> tem_i;                stack<char> tem_c;                while(symbol.top()!='('){                    tem_i.push(num.top());                    num.pop();                    tem_c.push(symbol.top());                    symbol.pop();                }                symbol.pop();                while(!tem_c.empty()){                    char c=tem_c.top();                    tem_c.pop();                    if(c=='+'){                        int a=tem_i.top();                        tem_i.pop();                        int b=tem_i.top();                        tem_i.pop();                        tem_i.push(a+b);                    }                    if(c=='-'){                        int a=tem_i.top();                        tem_i.pop();                        int b=tem_i.top();                        tem_i.pop();                        tem_i.push(a-b);                    }                }                num.push(tem_i.top());                tem_i.pop();            }        }        stack<int> tem_i;        stack<char> tem_c;        while(!symbol.empty()){            tem_i.push(num.top());            num.pop();            tem_c.push(symbol.top());            symbol.pop();        }        while(!tem_c.empty()){                    char c=tem_c.top();                    tem_c.pop();                    if(c=='+'){                        int a=tem_i.top();                        tem_i.pop();                        int b=tem_i.top();                        tem_i.pop();                        tem_i.push(a+b);                    }                    if(c=='-'){                        int a=tem_i.top();                        tem_i.pop();                        int b=tem_i.top();                        tem_i.pop();                        tem_i.push(a-b);                    }        }        return tem_i.top();    }    int stoi(string s){        int res=0;        for(int i=0;i<s.length();i++){            res=res*10+(s[i]-'0');        }        return res;    }};

转载于:https://www.cnblogs.com/yanqi110/p/5112842.html


最新回复(0)