题目:
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