224. Basic Calculator

 

该题要根据中缀表达式算出结果。这题参考了链接:

https://blog.csdn.net/tc_to_top/article/details/52348800

的方法2编写的,主要思路是递归。

代码如下:

 

 1 class Solution {
 2     public int calculate(String s) {
 3         if(s.length() == 0){
 4             return 0;
 5         }
 6         
 7         s = "(" + s + ")";
 8         int[] pos = {0};
 9         
10         return eval(s, pos);
11     }
12     
13     private static int eval(String s, int[] pos){
14         int val = 0, i = pos[0], sign = 1, num = 0;
15         
16         while(i < s.length()){
17             char c=s.charAt(i);
18             switch(c){
19                 case '+':val = val + sign*num; num = 0; sign = 1; i++; break;
20                 case '-':val = val + sign*num; num = 0; sign =-1; i++; break;
21                 case '(':pos[0] = i + 1; val = val + sign*eval(s, pos); i = pos[0]; break;
22                 case ')':pos[0] = i + 1; return val + sign*num;
23                 case ' ':i++; continue;
24                 default:num = num * 10 + c - '0'; i++;
25             }
26         }
27         return val;
28     }
29 }

 

END

posted @ 2018-04-26 14:55  sysu_kww  阅读(105)  评论(0编辑  收藏  举报