Leetcoe224 计算器
发布日期:2022-09-10 02:26:32 浏览次数:8 分类:技术文章

本文共 2047 字,大约阅读时间需要 6 分钟。

class Solution {
public: //+-*计算 int func(int a,int b,char op){
if(op=='+') return a+b; else if(op=='-') return a-b; else if(op=='*') return a*b; else return a/b; return 0; } //运算符优先级 int getpriority(char op){
if(op=='+'||op=='-') return 1; else return 2; return 0; } //越界或者遇到左括号返回 vector
help(string s,int index){
stack
nums;//操作数栈 stack
ops;//运算符栈 int i=index; while(i
='0'&&s[i]<='9'){
//当前为数字,继续寻找数字,然后将操作数入栈 int cur=0; while(s[i] >= '0' && s[i] <= '9') cur = cur * 10 + (s[i++] - '0'); nums.push(cur); }else if(s[i]!='('){
//当前为运算符,判断优先级 if(nums.empty()&&s[i]=='-'){
nums.push(0); }else if(ops.empty()||getpriority(s[i])>getpriority(ops.top())){
ops.push(s[i++]); }else{
while(!ops.empty()&&getpriority(s[i])<=getpriority(ops.top())){
int num1=nums.top(); nums.pop(); int num2=nums.top(); nums.pop(); char op=ops.top(); ops.pop(); int res=func(num2,num1,op); nums.push(res); } ops.push(s[i++]); } }else{
//遇到左括号,继续递归,将子过程返回的结果压入栈中,当前位置为子过程结束位置的下一个位置 auto res=help(s,i+1); nums.push(res[0]); i=res[1]+1; } } while(!ops.empty()){
int num1=nums.top(); nums.pop(); int num2=nums.top(); nums.pop(); char op=ops.top(); ops.pop(); int res=func(num2,num1,op); nums.push(res); } return {
nums.top(),i}; } int calculate(string s) {
return help(s,0)[0]; }};

转载地址:https://blog.csdn.net/qq_39240107/article/details/125896733 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:lee上有趣题目
下一篇:leetcod刷题计划Day11

发表评论

最新留言

表示我来过!
[***.240.166.169]2024年04月11日 13时44分06秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章