【Leetcode】150. Evaluate Reverse Polish Notation(栈)(算数模拟)

蔚落 2022-02-03 23:19 248阅读 0赞

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

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

Note:

  • Division between two integers should truncate toward zero.
  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.

Example 1:

  1. Input: ["2", "1", "+", "3", "*"]
  2. Output: 9
  3. Explanation: ((2 + 1) * 3) = 9

Example 2:

  1. Input: ["4", "13", "5", "/", "+"]
  2. Output: 6
  3. Explanation: (4 + (13 / 5)) = 6

Example 3:

  1. Input: ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
  2. Output: 22
  3. Explanation:
  4. ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
  5. = ((10 * (6 / (12 * -11))) + 17) + 5
  6. = ((10 * (6 / -132)) + 17) + 5
  7. = ((10 * 0) + 17) + 5
  8. = (0 + 17) + 5
  9. = 17 + 5
  10. = 22

题目大意:

给出字符串,其中每个算式先给出运算的左右两个部分,再给出运算符。

解题思路:

使用栈,不难看出当遇到运算符时,我们都会找前面的两个数计算之后再丢入栈内。

  1. class Solution {
  2. private:
  3. vector<int> nums;
  4. bool valid(string a){
  5. if((a[0]=='+'||a[0]=='-'||a[0]=='*'||a[0]=='/')&&a.length()==1) return false;
  6. return true;
  7. }
  8. int com_next(string s){
  9. int len_size = nums.size();
  10. int a, b;
  11. a = nums[len_size-2], b = nums[len_size-1];
  12. nums.pop_back();
  13. nums.pop_back();
  14. if(s=="+") return a+b;
  15. if(s=="-") return a-b;
  16. if(s=="*") return a*b;
  17. if(s=="/") return a/b;
  18. return 0;
  19. }
  20. int str2int(string l){
  21. int end_idx = 0;
  22. if(l[0]=='-') end_idx = 1;
  23. int len_size = l.length();
  24. int ans = 0, t=0;
  25. for(int i = len_size-1;i>=end_idx;i--){
  26. ans+=((l[i]-'0')*pow(10,t++));
  27. }
  28. return (end_idx==1)?-1*ans:ans;
  29. }
  30. public:
  31. int evalRPN(vector<string>& tokens) {
  32. if(tokens.size()==0) return 0;
  33. for(int i=0;i<tokens.size();i++){
  34. if(valid(tokens[i])){
  35. nums.push_back(str2int(tokens[i]));
  36. }else{
  37. nums.push_back(com_next(tokens[i]));
  38. }
  39. }
  40. return nums[0];
  41. }
  42. };

发表评论

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

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

相关阅读