LeetCode

来源:互联网 发布:苹果数据线线序 编辑:程序博客网 时间:2024/06/06 12:39

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7" 3/2 " = 1" 3+5 / 2 " = 5

Note: Do not use the eval built-in library function.


计算一个字符串的值。

利用一个栈,将数字计算出来丢进去(+-注意改变正负),并在遍历时计算乘除法。最后只要将栈中数字都加起来即可。时间复杂度O(n),空间复杂度O(n)

class Solution {public:    int calculate(string s) {        stack<int> st;        int sum = 0;        char sign = '+';        for (int i = 0; i < s.length(); ++i) {            if (s[i] == ' ') continue;            if (s[i] >= '0' && s[i] <= '9') {                sum = sum * 10 + (s[i] - '0');                continue;            }            if (sign == '+') {                st.push(sum);                sum = 0;            }            else if (sign == '-') {                st.push(-sum);                sum = 0;            }            else if (sign == '*') {                int num = st.top();                st.pop();                st.push(num * sum);                sum = 0;            }            else if (sign == '/') {                int num = st.top();                st.pop();                st.push(num / sum);                sum = 0;            }            sign = s[i];        }        if (sign == '+') {            st.push(sum);            sum = 0;        }        else if (sign == '-') {            st.push(-sum);            sum = 0;        }        else if (sign == '*') {            int num = st.top();            st.pop();            st.push(num * sum);            sum = 0;        }        else if (sign == '/') {            int num = st.top();            st.pop();            st.push(num / sum);            sum = 0;        }                int ans = 0;        while (!st.empty()) {            ans += st.top();            st.pop();        }        return ans;    }};

原创粉丝点击