Basic Calculator(LeetCode)

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -non-negative integers and empty spaces .

Example 1:

Input: "1 + 1"
Output: 2

Example 2:

Input: " 2-1 + 2 "
Output: 3

Example 3:

Input: "(1+(4+5+2)-3)+(6+8)"
Output: 23
Note:
  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

实现一个简单的字符串计算器,只有加减和括号。

思路:第一步是取数和运算符,取到一个完整的数,得到两个数之间的符号,才能进行加减;

第二步是处理括号,没遇到一个左括号就相当于里面是一个完整的计算式,计算方法同第一步,遇到一个右括号停止。由于会有多个括号,所以暂时的结果要先记下来,与这个暂时结果结合的符号也要记下来,这里选择stack。

法一:一次取一个字符的取数方式

class Solution {
public:
	int calculate(string s) {
		int res = 0, sign = 1;
		stack<int> st;
		int num = 0;
		for (char c:s) {
			if (isdigit(c)) {
				num = num*10 + c - '0';
			}
			else {
				res += sign * num;
				num = 0;//归0,准备计下一个数
				if (c == '+') {
					sign = 1;
				}
				if (c == '-') {
					sign = -1;
				}
				if (c == '(') {
					st.push(res);//记住暂时结果
					st.push(sign);//记住与暂时结果匹配的运算符
					res = 0;//清零进入下一次计算
					sign = 1;
				}
				if (c == ')') {
					res *= st.top(); st.pop();
					res += st.top(); st.pop();
				}
			}
			
		}
		res += sign * num;//加上最后一个数,因为它进不了第一个if的else
		return res;
	}
};

法二:一次取一个完整的数的取数方式

class Solution {
public:
    int calculate(string s) {
        int res = 0, sign = 1, n = s.size();
        stack<int> st;
        for (int i = 0; i < n; ++i) {
            char c = s[i];
            if (c >= '0') {
                int num = 0;
                while (i < n && s[i] >= '0') {//得到一个完整的数
                    num = 10 * num + s[i++] - '0';
                }
                res += sign * num;
                --i;//多计数的一个减去
            } else if (c == '+') {
                sign = 1;
            } else if (c == '-') {
                sign = -1;
            } else if (c == '(') {
                st.push(res);
                st.push(sign);
                res = 0;
                sign = 1;
            } else if (c == ')') {
                res *= st.top(); st.pop();
                res += st.top(); st.pop();
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/u014485485/article/details/80870612