using System; using System.Collections.Generic; class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 返回表达式的值 * @param s string字符串 待计算的表达式 * @return int整型 */ public int solve (string s) { s = s.Replace(" ", ""); Stack<int> nums = new Stack<int>(); List<char> num = new List<char>(); Stack<char> ops = new Stack<char>(); char op; nums.Push(0); for(int i = 0; i < s.Length; i++){ if(s[i] >= '0' && s[i] <= '9') num.Add(s[i]); else{ if(num.Count > 0){ nums.Push(ToNumber(num)); num.Clear(); } if(s[i] == '(') ops.Push('('); else if(s[i] == ')'){ while(ops.Peek() != '('){ DoSolve(nums, ops); } ops.Pop(); } else if(s[i] == '+' || s[i] == '-'){ while(ops.Count > 0 && ((op = ops.Peek()) == '+' || op == '-' || op == '*')){ DoSolve(nums, ops); } ops.Push(s[i]); } else if(s[i] == '*'){ while(ops.Count > 0 && ops.Peek() == '*'){ DoSolve(nums, ops); } ops.Push(s[i]); } } } if(num.Count > 0){ nums.Push(ToNumber(num)); num.Clear(); } while(ops.Count > 0){ DoSolve(nums, ops); } return nums.Pop(); } public int ToNumber(List<char> num){ char[] array = num.ToArray(); return int.Parse(new string(array)); } public void DoSolve(Stack<int> nums, Stack<char> ops){ int num2 = nums.Pop(); int num1 = nums.Pop(); char op1 = ops.Pop(); switch(op1){ case '+': nums.Push(num1 + num2); break; case '-': nums.Push(num1 - num2); break; case '*': nums.Push(num1 * num2); break; default: break; } } }