Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers, +
, -
, *
, /
operators and empty spaces . The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 " 3/2 " = 1 " 3+5 / 2 " = 5
思路:
将中缀表达式转化为后缀表达式然后求值。但是这道题没有括号,所以实现起来相对简单,也有比较简便的方法,就是第一遍先处理乘除法,然后第二遍处理加减法,这样效率高一点。抱着学习如何将中缀表达式转化为后缀表达式的态度,还是用后缀表达式来做的 - -。
C++:
1 class Solution { 2 public: 3 4 //构造函数 5 Solution() 6 { 7 //设置运算的优先级 8 priorityMap.insert(make_pair(‘+‘, 0)); 9 priorityMap.insert(make_pair(‘-‘, 0)); 10 priorityMap.insert(make_pair(‘*‘, 1)); 11 priorityMap.insert(make_pair(‘/‘, 1)); 12 } 13 14 //中缀表达式转换为后缀表达式 15 void inFix2PostFix(string& s, vector<int>& PostFix) 16 { 17 stack<char> stk; 18 19 for(int i = 0; i < s.size(); i++) 20 { 21 if(s[i] >= ‘0‘ && s[i] <= ‘9‘) 22 { 23 int sum = s[i++] - ‘0‘; 24 25 while(s[i] >= ‘0‘ && s[i] <= ‘9‘) 26 { 27 sum = sum*10 + s[i] - ‘0‘; 28 i++; 29 } 30 31 PostFix.push_back(sum); 32 33 i--; 34 } 35 36 if(s[i] == ‘+‘ || s[i] == ‘-‘ || s[i] == ‘*‘ || s[i] == ‘/‘) 37 { 38 while(!stk.empty()) 39 { 40 char topChar = stk.top(); 41 if(priorityMap[topChar] >= priorityMap[s[i]]) 42 { 43 PostFix.push_back(topChar - 48); 44 stk.pop(); 45 } 46 else 47 { 48 break; 49 } 50 } 51 stk.push(s[i]); 52 } 53 } 54 55 while(!stk.empty()) 56 { 57 PostFix.push_back(stk.top() - 48); 58 stk.pop(); 59 } 60 } 61 62 //计算后缀表达式的值 63 int calculatePostFix(vector<int>& PostFix) 64 { 65 stack<int> stk; 66 67 for(int i = 0; i < PostFix.size(); i++) 68 { 69 if(PostFix[i] >= 0) 70 { 71 stk.push(PostFix[i]); 72 continue; 73 } 74 75 int rhs = stk.top();//右操作数 76 stk.pop(); 77 int lhs = stk.top();//左操作数 78 stk.pop(); 79 80 if(PostFix[i] == -5) //加 81 { 82 stk.push(lhs + rhs); 83 } 84 if(PostFix[i] == -3)//减 85 { 86 stk.push(lhs - rhs); 87 } 88 if(PostFix[i] == -6)//乘 89 { 90 stk.push(lhs * rhs); 91 } 92 if(PostFix[i] == -1)//除 93 { 94 stk.push(lhs / rhs); 95 } 96 } 97 98 return stk.top(); 99 } 100 101 int calculate(string s) { 102 int len = s.size(); 103 if(len == 0) 104 return 0; 105 106 vector<int> PostFix; 107 108 inFix2PostFix(s, PostFix); 109 110 return calculatePostFix(PostFix); 111 } 112 private: 113 114 map<char, int> priorityMap; 115 };
时间: 2024-10-23 05:59:49