标签:
题目描述:public class Solution { public int Calculate(string s) { // two stack var opStack = new Stack<string>(); var numStack = new Stack<int>(); var n = ""; // if number , push number stack for(var i = 0;i < s.Length; i++){ if(s[i] == ‘ ‘){ continue; } // if (, +,- , push op stack if(s[i] == ‘(‘ || s[i] == ‘+‘ || s[i] == ‘-‘){ opStack.Push(s[i].ToString()); } // if ). pop op stack, pop 2 from number stack, until reach ‘(‘ else if(s[i] == ‘)‘){ var poped = false; if(opStack.Count > 0 && opStack.Peek() == "("){ poped = true; opStack.Pop(); } while(opStack.Count > 0 && opStack.Peek() != "("){ var n1 = numStack.Pop(); var n2 = numStack.Pop(); var o = opStack.Pop(); numStack.Push(Calc(n1, n2, o)); } if(!poped && opStack.Count > 0 && opStack.Peek() == "("){ opStack.Pop(); } } // push num into numStack, try calc until reach ‘(‘ else { // parse out number var valid = "0123456789"; if(valid.Contains(s[i])){ n += s[i]; if(i == s.Length - 1 || !valid.Contains(s[i+1])){ numStack.Push(int.Parse(n)); n = ""; while(opStack.Count > 0 && opStack.Peek() != "(") { var o = opStack.Pop(); var n1 = numStack.Pop(); var n2 = numStack.Pop(); numStack.Push(Calc(n1,n2,o)); } } } } } // pop the rest ops in opstack and numbers in number stack while(opStack.Count > 0){ var o = opStack.Pop(); if(o != "+" && o != "-"){ continue; } var n1 = numStack.Pop(); var n2 = numStack.Pop(); numStack.Push(Calc(n1,n2,o)); } return numStack.Pop(); } public int Calc(int n1, int n2, string op){ switch(op) { case "+" : return n1 + n2; case "-" : return n2 - n1; default : throw new NotSupportedException(); } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/48649985