【LeetCode 227】Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

思路:

  将中缀表达式转化为后缀表达式然后求值。但是这道题没有括号,所以实现起来相对简单,也有比较简便的方法,就是第一遍先处理乘除法,然后第二遍处理加减法,这样效率高一点。抱着学习如何将中缀表达式转化为后缀表达式的态度,还是用后缀表达式来做的 - -。

C++:

  1 class Solution {
  2 public:
  3
  4     //构造函数
  5     Solution()
  6     {
  7         //设置运算的优先级
  8         priorityMap.insert(make_pair(‘+‘, 0));
  9         priorityMap.insert(make_pair(‘-‘, 0));
 10         priorityMap.insert(make_pair(‘*‘, 1));
 11         priorityMap.insert(make_pair(‘/‘, 1));
 12     }
 13
 14     //中缀表达式转换为后缀表达式
 15     void inFix2PostFix(string& s, vector<int>& PostFix)
 16     {
 17         stack<char> stk;
 18
 19         for(int i = 0; i < s.size(); i++)
 20         {
 21             if(s[i] >= ‘0‘ && s[i] <= ‘9‘)
 22             {
 23                 int sum = s[i++] - ‘0‘;
 24
 25                 while(s[i] >= ‘0‘ && s[i] <= ‘9‘)
 26                 {
 27                     sum = sum*10 + s[i] - ‘0‘;
 28                     i++;
 29                 }
 30
 31                 PostFix.push_back(sum);
 32
 33                 i--;
 34             }
 35
 36             if(s[i] == ‘+‘ || s[i] == ‘-‘ || s[i] == ‘*‘ || s[i] == ‘/‘)
 37             {
 38                 while(!stk.empty())
 39                 {
 40                     char topChar = stk.top();
 41                     if(priorityMap[topChar] >= priorityMap[s[i]])
 42                     {
 43                         PostFix.push_back(topChar - 48);
 44                         stk.pop();
 45                     }
 46                     else
 47                     {
 48                         break;
 49                     }
 50                 }
 51                 stk.push(s[i]);
 52             }
 53         }
 54
 55         while(!stk.empty())
 56         {
 57             PostFix.push_back(stk.top() - 48);
 58             stk.pop();
 59         }
 60     }
 61
 62     //计算后缀表达式的值
 63     int calculatePostFix(vector<int>& PostFix)
 64     {
 65         stack<int> stk;
 66
 67         for(int i = 0; i < PostFix.size(); i++)
 68         {
 69             if(PostFix[i] >= 0)
 70             {
 71                 stk.push(PostFix[i]);
 72                 continue;
 73             }
 74
 75             int rhs = stk.top();//右操作数
 76             stk.pop();
 77             int lhs = stk.top();//左操作数
 78             stk.pop();
 79
 80             if(PostFix[i] == -5) //加
 81             {
 82                 stk.push(lhs + rhs);
 83             }
 84             if(PostFix[i] == -3)//减
 85             {
 86                 stk.push(lhs - rhs);
 87             }
 88             if(PostFix[i] == -6)//乘
 89             {
 90                 stk.push(lhs * rhs);
 91             }
 92             if(PostFix[i] == -1)//除
 93             {
 94                 stk.push(lhs / rhs);
 95             }
 96         }
 97
 98         return  stk.top();
 99     }
100
101     int calculate(string s) {
102         int len = s.size();
103         if(len == 0)
104             return 0;
105
106         vector<int> PostFix;
107
108         inFix2PostFix(s, PostFix);
109
110         return calculatePostFix(PostFix);
111     }
112 private:
113
114     map<char, int> priorityMap;
115 };
时间: 2024-10-23 05:59:49

【LeetCode 227】Basic Calculator II的相关文章

【LeetCode 229】Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space. 思路: [LeetCode 169]Majority Element 的拓展,这回要求的是出现次数超过三分之一次的数字咯,动动我们的大脑思考下,这样的数最多会存在几个呢,当然是2个嘛.因此,接着上一题的方

【Leetcode】Basic Calculator II

题目链接:https://leetcode.com/problems/basic-calculator-ii/ 题目: Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division s

【Leetcode 167】Two Sum II - Input array is sorted

问题描述:给出一个升序排列好的整数数组,找出2个数,它们的和等于目标数.返回这两个数的下标(从1开始),其中第1个下标比第2个下标小. Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2 分析:在排序好的数组中进行查找,很容易想到用二分查找的思想.这里相当于是二分查找两个数,可以把最小值和最大值作为起点求和(sum). 若sum<target,则需要把较小元素也就是low处元素变大,此时不能直接把mid赋值给low,

【LeetCode】227. Basic Calculator II

Basic Calculator II Implement a basic calculator to evaluate a simple expression string. The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero. You may assu

LeetCode 227. 基本计算器 II(Basic Calculator II)

227. 基本计算器 II 227. Basic Calculator II 题目描述 实现一个基本的计算器来计算一个简单的字符串表达式的值. 字符串表达式仅包含非负整数,+,-,*,/ 四种运算符和空格.整数除法仅保留整数部分. LeetCode227. Basic Calculator II中等 示例?1: 输入: "3+2*2" 输出: 7 示例 2: 输入: " 3/2 " 输出: 1 示例 3: 输入: " 3+5 / 2 " 输出:

LeetCode OJ Basic Calculator II

Basic Calculator II 题目 思路 和这个一样:Basic Calculator I 代码 class ExpressionTransformation { public: string trans_to_postfix_expression_to_s(string); // 将得到的表达式转化为后缀表达式 long long int calculate_from_postfix_expression(); // 根据后缀表达式计算值 private: vector<string

Leetcode solution 772: Basic Calculator III

Problem Statement Implement a basic calculator to evaluate a simple expression string. The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces . The expression string cont

【LeetCode OJ】Sum Root to Leaf Numbers

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 # Definition for a  binary tree node # class TreeNode: #     def __init__(self, x): #         self.val = x #         self.left = No

【LeetCode OJ】Longest Consecutive Sequence

Problem Link: http://oj.leetcode.com/problems/longest-consecutive-sequence/ This problem is a classical problem where we can reduce the running time by the help of hash table. By given a list of numbers, we can find the longest consecutive sequence b