您的位置:首页 > 其它

224. Basic Calculator

2015-11-25 07:26 471 查看
题目:

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


Note: Do not use the
eval
built-in library function

链接: http://leetcode.com/problems/basic-calculator/

题解:

刚开始以为要用和RPN一样的方法,其实不是的。可以one pass遍历整个数组并且得到结果。 需要使用一个栈来cache括号这种情况。

Time Complexity - O(n), Space Complexity - O(n)。

public class Solution {
public int calculate(String s) {
if(s == null || s.length() == 0)
return 0;
Stack<Integer> stack = new Stack<>();
int result = 0, curNum = 0, sign = 1;

for(int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if(c == ' ')
continue;
else if(Character.isDigit(c))
curNum = curNum * 10 + (int)(c - '0');
else if (c == '+') {
result += sign * curNum;
curNum = 0;
sign = 1;
} else if (c == '-') {
result += sign * curNum;
curNum = 0;
sign = -1;
} else if (c == '(') {
stack.push(result);
stack.push(sign);
curNum = 0;
sign = 1;
result = 0;
} else if (c == ')') {
result += sign * curNum;
curNum = 0;
if(!stack.isEmpty())
result *= stack.pop();
if(!stack.isEmpty())
result += stack.pop();
}
}

if(curNum != 0)
result += sign * curNum;

return result;
}
}


Reference:
https://leetcode.com/discuss/39553/iterative-java-solution-with-stack https://leetcode.com/discuss/41868/java-solution-stack https://leetcode.com/discuss/39479/simple-c-in-24-ms
  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: