ID | Title | Difficulty | |
---|---|---|---|
Loading... |
224. Basic Calculator
Hard
LeetCode
Math, String, Stack, Recursion
Problem
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "1 + 1"
Output: 2
Example 2:
Input: s = " 2-1 + 2 "
Output: 3
Example 3:
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
Code
class Solution {
public int calculate(String s) {
if(s == null || s.length() == 0) return 0;
Stack<String> stack = new Stack<>();
String sign = "+";
int i = 0;
while(i < s.length()){
char c = s.charAt(i);
if(c ==' '){
i++;
continue;
}else if(c == '('){
stack.push(sign);
stack.push("(");
sign="+";
} else if (c == ')'){
int temp = 0;
while(stack.peek() != "("){
temp += Integer.valueOf(stack.pop());
}
stack.pop();
if(stack.pop() == "+"){
stack.push(temp + "");
} else {
stack.push(-temp + "");
}
} else if(c == '+'){
sign = "+";
} else if (c == '-'){
sign = "-";
} else {
int temp = c - '0';
while(i + 1 < s.length() && Character.isDigit(s.charAt(i + 1))){
temp = temp * 10 + (s.charAt(i + 1) - '0');
i++;
}
if(sign == "+"){
stack.push(temp + "");
} else {
stack.push(-temp + "");
}
}
i++;
}
int res = 0;
while(!stack.isEmpty()){
res += Integer.valueOf(stack.pop());
}
return res;
}
}
按 <- 键看上一题!
223. Rectangle Area
按 -> 键看下一题!
225. Implement Stack using Queues