码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 224: Basic Calculator

时间:2017-12-03 11:25:00      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:uil   note   ati   har   should   style   leetcode   empty   eva   

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.

 

 

 1 public class Solution {
 2     public int Calculate(string s) {
 3         var nums = new Stack<int>();
 4         var ops = new Stack<char>();
 5         
 6         var sc = s.ToCharArray();
 7         
 8         for (int i = 0; i < sc.Length; i++)
 9         {
10             if (sc[i] ==  )
11             {
12                 continue;
13             }
14             else if (sc[i] == ( || sc[i] == + || sc[i] == - )
15             {
16                 ops.Push(sc[i]);
17             }
18             else if (sc[i] == ))
19             {
20                 // the top should be ‘(‘
21                 ops.Pop();
22                 
23                 if (ops.Count > 0)
24                 {
25                     var op = ops.Pop();
26                     var n2 = nums.Pop();
27                     var n1 = nums.Pop();
28 
29                     nums.Push(Calculate(n1, n2, op));
30                 }
31             }
32             else
33             {
34                 int n1 = 0;
35                 
36                 while (i < sc.Length && (int)sc[i] >= (int)0 && (int)sc[i] <= (int)9)
37                 {
38                     n1 = n1 * 10 + (int)sc[i] - (int)0;
39                     i++;
40                 }
41                 
42                 i--;
43                 
44                 if (ops.Count == 0 || ops.Peek() == ()
45                 {
46                     nums.Push(n1);
47                 }
48                 else 
49                 {
50                     nums.Push(Calculate(nums.Pop(), n1, ops.Pop()));
51                 }
52             }
53         }
54         
55         return nums.Pop();
56     }
57     
58     private int Calculate(int n1, int n2, char op)
59     {
60         return op == + ? n1 + n2 : n1 - n2;
61     }
62 }

 

 
 
 

Leetcode 224: Basic Calculator

标签:uil   note   ati   har   should   style   leetcode   empty   eva   

原文地址:http://www.cnblogs.com/liangmou/p/7965331.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!