LeetCode 224. Basic Calculator

原题链接在这里:https://leetcode.com/problems/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 

题解:

The final resut is num1 + o1 * num2.

First remvoe all the whitespaces.

 

遇到数字位,看后一位是否为数字,若是位数字,当前位需要进十. Update num2.

For operator, if it is the first operator or right after "(", just update o1. Otherwise, num1 = num1 + o1 * num2. Then update o1 and reset o1 and num2.

For "(", push into stack. For ")", cur = num1 + o1 * num2. pop the stack and num2 = cur.

Time Complexity: O(s.length()).

Space: O(s.length()), stack space.

AC Java: 

 1 class Solution {
 2     public int calculate(String s) {
 3         if(s == null || s.length() == 0){
 4             return 0;
 5         }
 6 
 7         s = s.replaceAll("\\s+", "");
 8         int num1 = 0;
 9         int o1 = 1;
10         int num2 = 1;
11         Stack<Integer> stk = new Stack<>();
12         int n = s.length();
13         for(int i = 0; i < n; i++){
14             char c = s.charAt(i);
15             if(Character.isDigit(c)){
16                 int cur = (int)(c - '0');
17                 while(i + 1 < n && Character.isDigit(s.charAt(i + 1))){
18                     cur = cur * 10 + (int)(s.charAt(i + 1) - '0');
19                     i++;
20                 }
21 
22                 num2 = cur;
23             }else if(c == '+' || c == '-'){
24                 if(c == '-' && (i == 0 || s.charAt(i-1) == '(')){
25                     o1 = -1;
26                     continue;
27                 }
28 
29                 num1 = num1 + o1 * num2;
30                 o1 = c == '+' ? 1 : -1;
31                 num2 = 1;
32             }else if(c == '('){
33                 stk.push(num1);
34                 stk.push(o1);
35                 stk.push(num2);
36 
37                 num1 = 0;
38                 o1 = 1;
39                 num2 = 1;
40             }else if(c == ')'){
41                 int cur = num1 + o1 * num2;
42                 num2 = stk.pop();
43                 o1 = stk.pop();
44                 num1 = stk.pop();
45                 num2 = cur;
46             }
47         }
48 
49         return num1 + o1 * num2;
50     }
51 }

 

类似Evaluate Reverse Polish Notation.

跟上Basic Calculator II.

posted @ 2015-08-21 09:42  Dylan_Java_NYC  阅读(326)  评论(0编辑  收藏  举报