150. 逆波兰表达式求值
知识点
字符串倒置
#include <cstring> #include <algorithm> int main() { string str1; cin>>str1; cout<<"原始字符串是:"<<str1<<endl; reverse(str1.begin(),str1.end()); cout<<"转换后的字符串是:"<<str1<<endl; return 0; }
string转int
string num; int tmp = stoi(num);
小白解法
class Solution { public: int evalRPN(vector<string> &tokens) { stack<int> stk; unordered_map<string, int> Hash = { {"+", 1}, {"-", 2}, {"*", 3}, {"/", 4}}; for (auto it : tokens) { if (Hash.count(it)) { int b = stk.top(); stk.pop(); int a = stk.top(); stk.pop(); int tmp; switch (Hash[it]) { case 1: tmp = a + b; break; case 2: tmp = a - b; break; case 3: tmp = a * b; break; case 4: tmp = a / b; break; default: break; } stk.push(tmp); } else { stk.push(stoi(it)); } } return stk.top(); } };
这题很简单,但编译时出现了很多问题,首先要明确哈希表是<string,int> 映射的。所以下面初始化过程字符串要用双引号表示,整型应该不用引号表示。错误示范{'+','1'},正确的是{"+",1}