LeetCode 题解(115): Basic Calculator

题目:

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 .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23
题解:

在Basic Calculator II的基础上改的。不用求乘除,加入了求括号运算的递归。

C++版:

class Solution {
public:
	int calculate(string s) {
		queue<char> sign;
		stack<int> operand;
		for (int i = 0; i < s.length(); i++) {
			compute(operand, i, s);
			i--;
		}

		return addAll(operand);
	}

	void getNextNumber(int& pos, string& s, stack<int>& operand) {
		int result = s[pos++] - '0';
		while (isdigit(s[pos]) || s[pos] == ' ') {
			if (s[pos] == ' ') {
				pos++;
				continue;
			}
			else {
				result = result * 10 + (s[pos] - '0');
				pos++;
			}
		}
		operand.push(result);
		pos--;
	}

	int solver(string& s, int& i) {
		queue<char> sign;
		stack<int> operand;
		i++;
		while (s[i] != ')') {
			compute(operand, i, s);
		}
		
		return addAll(operand);
	}
	
	void compute(stack<int>& operand, int& i, string& s) {
	    if (isdigit(s[i])) {
				getNextNumber(i, s, operand);
			}
			else if (s[i] == '-') {
				i++;
				while (s[i] == ' ')
					i++;
				if (isdigit(s[i])) {
					getNextNumber(i, s, operand);
					int old = operand.top();
					operand.pop();
					operand.push(old * (-1));
				}
				else {
					operand.push((-1) * solver(s, i));
				}
			}
			else if (s[i] == ' ' || s[i] == '+') {
				i++;
				return;
			}
			else if (s[i] == '(') {
				operand.push(solver(s, i));
			}
			i++;
	}
	
	int addAll(stack<int>& operand) {
	    int result = operand.top();
		operand.pop();
		while (!operand.empty()) {
			result += operand.top();
			operand.pop();
		}
		
		return result;
	}
};

Java版:

public class Solution {
    public int i = 0;

    public int calculate(String s) {
        Stack<Integer> operand = new Stack<>();
        while(i < s.length()) {
            calculate(s, operand);
        }

        return addAll(operand);
    }

    public void getNextNumber(String s, Stack<Integer> operand) {
        int result = s.charAt(i++) - '0';
        while(i < s.length() && (Character.isDigit(s.charAt(i)) || s.charAt(i) == ' ')) {
            if(s.charAt(i) == ' ') {
                i++;
                continue;
            } else {
                result = result * 10 + (s.charAt(i) - '0');
                i++;
            }
        }
        operand.push(result);
    }

    void calculate(String s, Stack<Integer> operand) {
        if(Character.isDigit(s.charAt(i))) {
            getNextNumber(s, operand);
        } else if(s.charAt(i) == ' ' || s.charAt(i) == '+') {
            i++;
            return;
        } else if(s.charAt(i) == '-') {
            i++;
            while(s.charAt(i) == ' ')
                i++;
            if(s.charAt(i) == '(') {
                i++;
                operand.push((-1) * solver(s));
            } else {
                getNextNumber(s, operand);
                int old = operand.pop();
                operand.push(old * (-1));
            }
        } else if(s.charAt(i) == '(') {
            i++;
            operand.push(solver(s));
        }
    }

    int solver(String s) {
        Stack<Integer> operand = new Stack<>();
        while(s.charAt(i) != ')') {
            calculate(s, operand);
        }
        i++;
        return addAll(operand);
    }

    int addAll(Stack<Integer> operand) {
        int result = operand.pop();
        while(!operand.empty())
            result += operand.pop();
        return result;
    }
}

Python版:

class Solution:
    # @param {string} s
    # @return {integer}
    def __init__(self):
        self.i = 0

    def calculate(self, s):
        operand = []
        while self.i < len(s):
            self.compute(s, operand)

        return self.addAll(operand)

    def findNextNumber(self, s, operand):
        result = ord(s[self.i]) - ord('0')
        self.i += 1
        while self.i < len(s) and (s[self.i].isdigit() or s[self.i] == ' '):
            if s[self.i] == ' ':
                self.i += 1
                continue
            else:
                result = result * 10 + (ord(s[self.i]) - ord('0'))
                self.i += 1
        operand.append(result)

    def compute(self, s, operand):
        if s[self.i].isdigit():
            self.findNextNumber(s, operand)
        elif s[self.i] == ' ' or s[self.i] == '+':
            self.i += 1
            return
        elif s[self.i] == '-':
            self.i += 1
            while s[self.i] == ' ':
                self.i += 1
            if s[self.i].isdigit():
                self.findNextNumber(s, operand)
                operand[-1] = operand[-1] * (-1)
            else:
                self.i += 1
                operand.append(self.solver(s) * (-1))
        elif s[self.i] == '(':
            self.i += 1
            operand.append(self.solver(s))

    def solver(self, s):
        operand = []
        while s[self.i] != ')':
            self.compute(s, operand)
        self.i += 1
        return self.addAll(operand)

    def addAll(self, operand):
        result = operand[-1]
        operand.pop()
        while len(operand) != 0:
            result += operand[-1]
            operand.pop()
        return result


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值