LeetCode 题解(113): Basic Calculator II

题目:

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.

题解:

核心是找下一个操作数,操作数可是一个字符或多个字符。注意若为空格或“+”皆可忽略,最后计算堆栈中所有操作数的和。

class Solution {
public:
	int calculate(string s) {
		queue<char> sign;
		stack<int> operand;
		for (int i = 0; i < s.length(); i++) {
			if (isdigit(s[i])) {
				getNextNumber(i, s, operand);
			}
			else if (s[i] == '-') {
				char current = s[i];
				i++;
				while (!isdigit(s[i]))
					i++;
				getNextNumber(i, s, operand);
				if (current == '-') {
					int old = operand.top();
					operand.pop();
					operand.push(old * (-1));
				}
			}
			else if (s[i] == ' ' || s[i] == '+') {
				continue;
			}
			else {
				int first = operand.top();
				operand.pop();
				int current = i;
				i++;
				while (!isdigit(s[i]))
					i++;
				getNextNumber(i, s, operand);
				int second = operand.top();
				operand.pop();
				if (s[current] == '*') {
					operand.push(first * second);
				}
				else {
					operand.push(first / second);
				}
			}
		}
		int result = operand.top();
		operand.pop();
		while (!operand.empty()) {
			result += operand.top();
			operand.pop();
		}

		return result;
	}

	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--;
	}
};

Java版:

public class Solution {
    public int calculate(String s) {
        Stack<Integer> operand = new Stack<>();
        for(int i = 0; i < s.length(); i++) {
            if(Character.isDigit(s.charAt(i))) {
                i = getNextNumber(s, i, operand);
            } else if(s.charAt(i) == ' ' || s.charAt(i) == '+') {
                continue;
            } else if(s.charAt(i) == '-') {
                i++;
                while(!Character.isDigit(s.charAt(i)))
                    i++;
                i = getNextNumber(s, i, operand);
                int old = operand.pop();
                operand.push(old * (-1));
            } else {
                int first = operand.pop();
                int current = i;
                i++;
                while(!Character.isDigit(s.charAt(i)))
                    i++;
                i = getNextNumber(s, i, operand);
                int second = operand.pop();
                if(s.charAt(current) == '*') {
                    operand.push(first * second);
                } else {
                    operand.push(first / second);
                }
            }
        }
                    
        int result = operand.pop();
        while(!operand.empty())
            result += operand.pop();
        return result;
    }
    
    public int getNextNumber(String s, int pos, Stack<Integer> operand) {
        int result = s.charAt(pos++) - '0';
        while(pos < s.length() && (Character.isDigit(s.charAt(pos)) || s.charAt(pos) == ' ')) {
            if(s.charAt(pos) == ' ') {
                pos++;
                continue;
            } else {
                result = result * 10 + (s.charAt(pos) - '0');
                pos++;
            }
        }
        operand.push(result);
        pos -= 1;
        return pos;
    }
}

Python版:

class Solution:
    # @param {string} s
    # @return {integer}
    def calculate(self, s):
        operand = []
        i = 0
        while i < len(s):
            if s[i].isdigit():
                i = self.findNextNumber(s, i, operand)
            elif s[i] == ' ' or s[i] == '+':
                i += 1
                continue
            elif s[i] == '-':
                i += 1
                while not s[i].isdigit():
                    i += 1
                i = self.findNextNumber(s, i, operand)
                old = operand[-1]
                operand.pop()
                operand.append(old * (-1))
            else:
                current = i
                i += 1
                first = operand[-1]
                operand.pop()
                while not s[i].isdigit():
                    i += 1
                i = self.findNextNumber(s, i, operand)
                second = operand[-1]
                operand.pop()
                if s[current] == '*':
                    operand.append(first * second)
                else:
                    if first < 0:
                        first = (-1) * first
                        x = (first / second) * (-1)
                    else:
                        x = first / second
                    operand.append(x)
                    
        result = operand[-1]
        operand.pop()
        while len(operand) != 0:
            result += operand[-1]
            operand.pop()
        return result
        
    def findNextNumber(self, s, pos, operand):
        result = ord(s[pos]) - ord('0')
        pos += 1
        while pos < len(s) and (s[pos].isdigit() or s[pos] == ' '):
            if s[pos] == ' ':
                pos += 1
                continue
            else:
                result = result * 10 + (ord(s[pos]) - ord('0'))
                pos += 1
        operand.append(result)
        return pos


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值