Evaluate Reverse Polish Notation 解题思路

来源:互联网 发布:鹊桥与淘宝联盟的使用 编辑:程序博客网 时间:2024/04/27 16:49

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
解题思路:首先判断字符串是数字还是操作符,在此处别忘了考虑负数;其次,如果为数字,提取出来,放进新建的数字容器s中,如果为操作符,取出容器s中最后添加进去的两个数字,进行相应运算。对于给定的所有字符串依次进行以上步骤即可完成题目要求,当然题目已经假定表达式合法并且有解。以下是代码:
bool isnum(string s)//判断是否为数字    {        if(s[0]>='0'&&s[0]<='9') return true;        if(s[0]=='-'&&s[1]>='0'&&s[1]<='9')return true;        else return false;    }    int getnum(string s)//提取数字    {        int result=0;        int i=0;        if(s[0]!='-')        {            while(s[i])            {            result*=10;            result+=(int)(s[i]-'0');            i++;            }            return result;        }        else        {            i=1;            while(s[i])            {            result*=10;            result+=(int)(s[i]-'0');            i++;            }            result=-result;            return result;        }    }    char getc(string s)//提取操作符    {        return (char)s[0];    }    int evalRPN(vector<string> &tokens) {        vector<int> result;        int n=tokens.size();        int temp=0,s=0;        for(int i=0;i<n;i++)        {            if(isnum(tokens[i]))            {                result.push_back(getnum(tokens[i]));                s++;            }            else            {                switch (getc(tokens[i])){                case '+':temp=0;                        temp+=result[s-1];                        result.erase(result.begin()+s-1);                        s--;                        temp+=result[s-1];                        result.erase(result.begin()+s-1);                        result.push_back(temp);                        continue;                case '-':temp=result[s-2]-result[s-1];                        result.erase(result.begin()+s-1);                        s--;                        result.erase(result.begin()+s-1);                        result.push_back(temp);                        continue;                case '*':temp=result[s-2]*result[s-1];                        result.erase(result.begin()+s-1);                        s--;                        result.erase(result.begin()+s-1);                        result.push_back(temp);                        continue;                case '/':temp=result[s-2]/result[s-1];                        result.erase(result.begin()+s-1);                        s--;                        result.erase(result.begin()+s-1);                        result.push_back(temp);                        continue;                }            }        }        return result[0];    }

0 0
原创粉丝点击