当前位置: 首页 > news >正文

Leetcode 227 Basic calculator

题意:写一个计算器,包括加减乘除

Input: s = “3+2*2”
Output: 7

链接
https://leetcode.com/problems/basic-calculator-iii/description/
https://leetcode.com/problems/basic-calculator-ii/description/

需要有一个operator stack以及一个num数字的stack,operator stack中的符号新来的优先级比后来的优先级要小的话那我就要计算
有个取数字的模版要记住:

if(isdigit(s[i])) {int j = i;while(j < s.size() && isdigit(s[j])) j++;int x = stoi(s.substr(i, j-i));num.push(x);i = j - 1;
class Solution {
public:int calculate(string s) {stack<int> num;stack<char> oper;unordered_map<char, int> pr = {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}, {'(', 0}};for(int i = 0; i < s.size(); i++) {if(isdigit(s[i])) {int j = i;while(j < s.size() && isdigit(s[j])) j++;int x = stoi(s.substr(i, j-i));num.push(x);i = j - 1;} else if(pr.count(s[i])) {while(oper.size() && pr[s[i]] <= pr[oper.top()]) {get(num, oper);}oper.push(s[i]);} else if(s[i] == ' ') {continue;} else if (s[i] == '(') {oper.push(s[i]);} else if (s[i] == ')') {while(oper.top()!= '(') {get(num, oper);}oper.pop();}}while(oper.size()) {get(num, oper);}return num.top();}void get(stack<int>& num, stack<char>& oper) {int num1 = num.top();num.pop();int num2 = num.top();num.pop();char op = oper.top();oper.pop();int result = 0;switch(op) {case '*': result = num1 * num2; break;case '+': result = num1 + num2; break;case '-': result = num2 - num1; break;case '/': result = num2 / num1; break;}num.push(result);}
};

http://www.mrgr.cn/news/50317.html

相关文章:

  • 阻塞队列相关的问题
  • Github 2024-10-15 Python开源项目日报 Top10
  • Python | Leetcode Python题解之第479题最大回文数乘积
  • 【Linux】解读信号的本质&相关函数及指令的介绍
  • DDPM代码详解(可用)
  • C语言复习概要(六)
  • 【2D/3D-Lidar-SLAM】 2D/3D激光SLAM以及GMapping 与 Cartographer
  • 开发规范 - mac系统1小时装机极速装机开发环境
  • 基于springboot+微信小程序校园自助打印管理系统(打印1)
  • Golang | Leetcode Golang题解之第479题最大回文数乘积
  • 大厂服务降级规范
  • 牛只行为及种类识别数据集18g牛只数据,适用于多种图像识别,目标检测,区域入侵检测等算法作为数据集。数据集中包括牛只行走,站立,进食,饮水等不同类型的数据
  • Forward Chaining(前向链推理)
  • iOS 打包/导出时提示图标错误,缺少某个规格的图标
  • 抽奖结果已出
  • 除了ConcurrentHashMap,还有哪些Java集合类在并发处理上有优化?
  • Vue开发中由错误These relative modules were not found 引起的问题思考及解决
  • maven项目package打包的时候遇到-source 1.5 中不支持 try-with-resources
  • SQL Injection | SQL 注入分类 —— 数据类型
  • 利用TDM在vscode中运行c语言