image.png

思路:

  • 利用堆栈进行逆波兰式求值
  • 如果遇到整数,就入栈
  • 如果遇到符号,就将最上面的两个数字弹栈,进行运算之后得到新的数字,并入栈
  • 最后一定只剩下一个数字,那个数字就是最终得数
  • 字符串转整数的细节比较繁琐

    代码:

  1. class Solution {
  2. public:
  3. int stringToNum(string num_string) {
  4. if (num_string == "*" || num_string == "/" || num_string == "+" || num_string == "-") {
  5. return 0x3f3f3f3f;
  6. }
  7. bool negative = false;
  8. int res_num = 0;
  9. int begin_pos = 0, end_pos = num_string.size() - 1;
  10. // 读掉符号
  11. if (num_string[0] == '-') {
  12. negative = true;
  13. begin_pos = 1;
  14. } else if (num_string[0] == '+') {
  15. begin_pos = 1;
  16. }
  17. for (int i = begin_pos; i <= end_pos; ++i) {
  18. res_num = (res_num * 10 + (num_string[i] - '0'));
  19. }
  20. return res_num * (negative == false ? 1 : -1);
  21. }
  22. int evalRPN(vector<string>& tokens) {
  23. stack<int> post_expr;
  24. int len_tokens = tokens.size();
  25. for (int i = 0; i < len_tokens; ++i) {
  26. if (stringToNum(tokens[i]) >= -200 && stringToNum(tokens[i]) <= 200) {
  27. post_expr.push(stringToNum(tokens[i]));
  28. } else {
  29. int num2 = post_expr.top();
  30. post_expr.pop();
  31. int num1 = post_expr.top();
  32. post_expr.pop();
  33. int new_num = 0;
  34. if (tokens[i] == "*") {
  35. new_num = num1 * num2;
  36. } else if (tokens[i] == "/") {
  37. new_num = num1 / num2;
  38. } else if (tokens[i] == "+") {
  39. new_num = num1 + num2;
  40. } else if (tokens[i] == "-") {
  41. new_num = num1 - num2;
  42. }
  43. post_expr.push(new_num);
  44. }
  45. }
  46. return post_expr.top();
  47. }
  48. };