您的位置:首页 > 编程语言 > Lua

evaluate-reverse-polish-notation(逆波兰表示求值)

2016-09-21 22:10 399 查看
//atoi (表示 ascii
to integer)是把字符串转换成整型数:int
atoi(const char *nptr);

//string.c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址。

class Solution {

public:

    int evalRPN(vector<string> &tokens) {

        stack<int> st;

        for (int i=0; i<tokens.size(); i++){

            string s = tokens[i];

            if (s=="+" || s=="-" || s=="*" || s=="/"){

                if (st.size()<2)

                    return 0;                  //表达式不合法

                int result = 0;

                int s2 = st.top();st.pop();

                int s1 = st.top();st.pop();

                if (s=="+"){

                    result = s1 + s2;

                }else if(s=="-"){

                    result = s1 - s2;

                }else if (s=="*"){

                    result = s1 * s2;

                }else if (s=="/"){

                    result = s1 / s2;

                }

                st.push(result);

            }else{

                st.push(atoi(s.c_str()));

            }

        }

        return st.top();

    }

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode