Evaluate Reverse Polish Notation--LeetCode

柔光的暖阳◎ 2022-08-07 13:35 243阅读 0赞

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Some examples:

  1. ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
  2. ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

思路:使用栈这个数据结构,只不过需要字符串和整数整数和字符串之间的转换

  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <stack>
  5. using namespace std;
  6. int strtoi(string& s)
  7. {
  8. if(s.length() == 0)
  9. return 0;
  10. int i=0,flag=1,result=0;
  11. if(s[0]=='-')
  12. {
  13. flag =-1;
  14. i++;
  15. }
  16. if(s[0]=='+')
  17. {
  18. i++;
  19. }
  20. for(;i<s.length();i++)
  21. {
  22. result *= 10;
  23. result += (s[i]-'0');
  24. }
  25. return result*flag;
  26. }
  27. string itostr(int num)
  28. {
  29. int flag =1,count = num;
  30. if(num <0)
  31. {
  32. flag = 0;
  33. count = -count;
  34. }
  35. string result;
  36. while(count)
  37. {
  38. result += (count%10 +'0');
  39. count = count/10;
  40. }
  41. if(flag == 0)
  42. result += '-';
  43. reverse(result.begin(),result.end());
  44. return result;
  45. }
  46. int evalRPN(vector<string> &tokens)
  47. {
  48. stack<string> sk;
  49. int result =0,i,temp;
  50. string first,second;
  51. for(i=0;i<tokens.size();i++)
  52. {
  53. if(tokens[i]=="+"||tokens[i]=="-"||tokens[i]=="*"||tokens[i]=="/")
  54. {
  55. first = sk.top();
  56. sk.pop();
  57. second =sk.top();
  58. sk.pop();
  59. if(tokens[i] == "+")
  60. temp = strtoi(first)+strtoi(second);
  61. else if(tokens[i]=="-")
  62. temp = strtoi(first)-strtoi(second);
  63. else if(tokens[i]=="*")
  64. temp = strtoi(first)*strtoi(second);
  65. else
  66. temp = strtoi(second)/strtoi(first);
  67. first = itostr(temp);
  68. sk.push(first);
  69. }
  70. else
  71. sk.push(tokens[i]);
  72. }
  73. first = sk.top();
  74. result = strtoi(first);
  75. return result;
  76. }
  77. int main()
  78. {
  79. string array[]={"4", "13", "5", "/", "+"};
  80. vector<string> tokens(array,array+sizeof(array)/sizeof(array[0]));
  81. cout<<evalRPN(tokens)<<endl;
  82. system("pause");
  83. return 0;
  84. }

发表评论

表情:
评论列表 (有 0 条评论,243人围观)

还没有评论,来说两句吧...

相关阅读