1 class Solution { 2 public: 3 /** 4 * 5 * @param tokens string字符串vector 6 * @return int整型 7 */ 8 int evalRPN(vector<string>& tokens) { 9 // write code here 10 stack<int> st; 11 for(auto token : tokens) { 12 if(token == "+" || token == "-" || token == "*" || token == "/"){ 13 int num_a = st.top();st.pop(); 14 int num_b = st.top();st.pop(); 15 if(token == "+" ) 16 st.push((num_b + num_a)); 17 if(token == "-" ) 18 st.push((num_b - num_a)); 19 if(token == "*" ) 20 st.push((num_b * num_a)); 21 if(token == "/" ) 22 st.push((num_b / num_a)); 23 } 24 else{ 25 stringstream strs; 26 strs << token; 27 int temp; 28 strs >> temp; 29 st.push(temp); 30 } 31 } 32 return st.top(); 33 } 34 };
根据操作符在后的特性,利用堆栈来完成计算。
关于stringstream操作详见:https://www.cnblogs.com/john1015/p/13216702.html
evaluate-reverse-polish-notati 计算逆波兰式的值
原文:https://www.cnblogs.com/john1015/p/13216576.html