逆波兰表达式
自己实现字符串转换数字函数
class Solution { public: int str_to_int(string s) { int result = 0; if (s[0] == '-') { for (int i = s.size() - 1, j = 0; i > 0; i--, j++) { result = result + (s[i] - '0') * pow(10, j); } result = -result; } else { for (int i = s.size()-1 , j =0; i >=0; i-- ,j++) { result = result + (s[i] - '0') *pow(10 ,j); } } return result; } int evalRPN(vector<string>& tokens) { stack<long> stack_t; long sum , num_1 ,num_2; for( int i=0 ; i<tokens.size();i++) { if (tokens[i] == "+") { num_2 = stack_t.top(); stack_t.pop(); num_1 = stack_t.top(); stack_t.pop(); stack_t.push(num_1 + num_2); } else if (tokens[i] == "-") { num_2 = stack_t.top(); stack_t.pop(); num_1 = stack_t.top(); stack_t.pop(); stack_t.push(num_1 - num_2); } else if (tokens[i] == "*") { num_2 = stack_t.top(); stack_t.pop(); num_1 = stack_t.top(); stack_t.pop(); stack_t.push(num_1 * num_2); } else if (tokens[i] == "/") { num_2 = stack_t.top(); stack_t.pop(); num_1 = stack_t.top(); stack_t.pop(); stack_t.push(num_1 / num_2); } else { stack_t.push(str_to_int(tokens[i])); // cout << str_to_int(tokens[i]) << endl; } } return stack_t.top(); } };
使用库函数
class Solution { public: int evalRPN(vector<string>& tokens) { stack<int> st; for (int i = 0; i < tokens.size(); i++) { if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") { int num1 = st.top(); st.pop(); int num2 = st.top(); st.pop(); if (tokens[i] == "+") st.push(num2 + num1); if (tokens[i] == "-") st.push(num2 - num1); if (tokens[i] == "*") st.push(num2 * num1); if (tokens[i] == "/") st.push(num2 / num1); } else { st.push(stoi(tokens[i])); } } int result = st.top(); st.pop(); // 把栈里最后一个元素弹出(其实不弹出也没事) return result; } };
二刷
class Solution { public: int evalRPN(vector<string>& tokens) { stack<long long> my_stack; for(int i=0 ; i<tokens.size() ;i++) { if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/") { long long tmp1 = my_stack.top(); my_stack.pop(); long long tmp2 = my_stack.top(); my_stack.pop(); // cout<<tmp2<<' '<<tmp1<<endl; if(tokens[i] == "+") my_stack.push( tmp2+tmp1); else if(tokens[i] == "-") my_stack.push( tmp2-tmp1); else if(tokens[i] == "*") my_stack.push(tmp2*tmp1); else if(tokens[i] == "/") my_stack.push(tmp2/tmp1 ); }else my_stack.push(stoi(tokens[i])); } return my_stack.top(); } };