Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- vector<string> ConvertToPostfix(string s){
- vector<string> pp;
- stack<char> op;
- string num = "";
- for(int i=0; i<s.size(); i++){
- if(isdigit(s[i])) num += s[i];
- else{
- if(num.size() > 0) pp.push_back(num);
- num = "";
- if(s[i] == '(') op.push('(');
- else if(s[i] == ')'){
- while(op.top() != '('){
- string ss = "";
- ss += op.top();
- pp.push_back(ss);
- op.pop();
- }
- op.pop();
- }
- else if(s[i] == '+' || s[i] == '-'){
- while(!op.empty() && (op.top()=='+' || op.top()=='-')){
- string ss = "";
- ss += op.top();
- pp.push_back(ss);
- op.pop();
- }
- op.push(s[i]);
- }
- }
- }
- if(num.size() > 0) pp.push_back(num);
- while(!op.empty()){
- string ss = "";
- ss += op.top();
- pp.push_back(ss);
- op.pop();
- }
- return pp;
- }
- int calcPostfix(vector<string>& pp){
- stack<int> st;
- for(auto it : pp){
- if(it == "+" || it == "-"){
- int num = st.top();
- st.pop();
- int num2 = st.top();
- st.pop();
- if(it == "+") st.push(num + num2);
- else st.push(num2 - num);
- }
- else st.push(stoi(it));
- }
- return st.top();
- }
- int calculate(string s) {
- string ss = "";
- for(int i=0; i<s.size(); i++){
- if(s[i] != ' ') ss += s[i];
- }
- string sss = "";
- for(int i=0; i<ss.size(); i++){
- if(ss[i] == '-'){
- if(!i || ss[i-1] == '+' || ss[i-1] == '-' || ss[i-1] == '(') sss += '0';
- }
- sss += ss[i];
- }
- auto v = ConvertToPostfix(sss);
- return calcPostfix(v);
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement