Untitled
unknown
plain_text
5 months ago
1.7 kB
5
Indexable
class Solution { public: int getNum(string& str, int i, int j){ int res= 0; for(int p=i;p<=j;p++){ res*=10; res+= (str[p]-'0'); } return res; } int calculate(string& str, int i, int left, int right){ if(str[i]=='-') return left- right; else if(str[i]=='+') return left+ right; else if(str[i]=='*') return left* right; else return left/right; } vector<int> solve(string& str, int i, int ss){ vector<int> res; if(i>=ss) return res; int operatorIndex= -1; int lastNum= -1; int st= i; for(int p= i;p<ss;p++){ if(str[p]<='9' && str[p]>='0') continue; if (str[p] == '+' || str[p] == '-' || str[p] == '*' || str[p] == '/' ){ if(operatorIndex ==-1) lastNum= getNum(str, st, p-1); else{ lastNum = calculate(str, operatorIndex, lastNum, getNum(str, st, p-1)); } operatorIndex= p; st= p+1; } vector<int> auxRes= solve(str, p+1, ss); for(auto resValue: auxRes){ res.push_back(calculate(str, operatorIndex, lastNum, resValue)); } } if(operatorIndex == -1)res.push_back(getNum(str, st, ss-1)); else res.push_back(calculate(str, operatorIndex,lastNum, getNum(str, st, ss-1))); return res; } vector<int> diffWaysToCompute(string expression) { int ss= expression.size(); return solve(expression, 0,ss); } };
Editor is loading...
Leave a Comment