[Leetcode] 770. Basic Calculator IV 解题报告

python-leetcode-770. 基本计算器 IV 这道题属于高难度的多项式计算问题。我们需要解析表达式,执行加减乘运算,并处理包含变量的多项式。作为计算表达式,其中包含整数、变量(仅小写字母)、加法。返回结果(若幂次相同,则按字典序排序变量)。,所以能在合理时间内处理大部分情况。我们需要计算表达式的值,并按。 阅读详情

题目:

Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1} (given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simplified expression, such as ["-1*a","14"]

  • An expression alternates chunks and symbols, with a space separating each chunk and symbol.
  • A chunk is either an expression in parentheses, a variable, or a non-negative integer.
  • A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like "2x" or "-x".

Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. For example, expression = "1 + 2 * 3" has an answer of ["7"].

The format of the output is as follows:

  • For each term of free variables with non-zero coefficient, we write the free variables within a term in sorted order lexicographically. For example, we would never write a term like "b*a*c", only "a*b*c".
  • Terms have degree equal to the number of free variables being multiplied, counting multiplicity. (For example, "a*a*b*c" has degree 4.) We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term.
  • The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.)  A leading coefficient of 1 is still printed.
  • An example of a well formatted answer is ["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"] 
  • Terms (including constant terms) with coefficient 0 are not included.  For example, an expression of "0" has an output of [].

Examples:

Input: expression = "e + 8 - a + 5", evalvars = ["e"], evalints = [1]
Output: ["-1*a","14"]

Input: expression = "e - 8 + temperature - pressure",
evalvars = ["e", "temperature"], evalints = [1, 12]
Output: ["-1*pressure","5"]

Input: expression = "(e + 8) * (e - 8)", evalvars = [], evalints = []
Output: ["1*e*e","-64"]

Input: expression = "7 - 7", evalvars = [], evalints = []
Output: []

Input: expression = "a * b * c + b * a * c * 4", evalvars = [], evalints = []
Output: ["5*a*b*c"]

Input: expression = "((a - b) * (b - c) + (c - a)) * ((a - b) + (b - c) * (c - a))",
evalvars = [], evalints = []
Output: ["-1*a*a*b*b","2*a*a*b*c","-1*a*a*c*c","1*a*b*b*b","-1*a*b*b*c","-1*a*b*c*c","1*a*c*c*c","-1*b*b*b*c","2*b*b*c*c","-1*b*c*c*c","2*a*a*b","-2*a*a*c","-2*a*b*b","2*a*c*c","1*b*b*b","-1*b*b*c","1*b*c*c","-1*c*c*c","-1*a*a","1*a*b","1*a*c","-1*b*c"]

Note:

  1. expression will have length in range [1, 250].
  2. evalvars, evalints will have equal lengths in range [0, 100].

思路:

很烦这种题目。。。

代码:

class Solution {
public:
    vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {
        unordered_map<string, int> eval;                // construct the map from evalvars to evalints
        for (int i = 0; i < evalvars.size(); ++i) {
            eval[evalvars[i]] = evalints[i];
        }
        auto resmp = helper(expression, eval);          // solve the problem
        vector<string> res;                             // construct the results
        for (auto param : resmp) {
            if (param.second == 0) {                    // skip zero coefficient
                continue;
            }
            res.push_back(to_string(param.second));
            for (auto p : param.first) {
                res.back() += "*" + p;
            }
        }
        return res;
    }
private:
    struct cmp {
        bool operator()(vector<string> x, vector<string> y) {   // sort terms by degree
            if (x.size() == y.size()) {
                return x < y;
            }
            else {
                return x.size() > y.size();
            }
        }
    };
    map<vector<string>, int, cmp> helper(string &expr, unordered_map<string, int> &eval) {
        map<vector<string>, int, cmp> local = {{{}, 1}}, global;
        string sub = "";
        int sign = 1, n = expr.size();
        for (int i = 0; i <= n; ++i) {
            if (i < n && expr[i] == ' ') {          // skip space
                continue;  
            }
            if (i < n && isalnum(expr[i])) {        // number and alphabet, add to sub expression
                sub += expr[i];
            }
            else if (i < n && expr[i] == '(') {     // parenthesis
                ++i;
                for (int p = 1; ; ++i) {            // get the sub expression in parenthesis
                    if (expr[i] == '(') {
                        ++p;
                    }
                    else if (expr[i] == ')') {
                        --p;
                    }
                    if (p == 0) {
                        break;
                    }
                    sub += expr[i];
                }
            }
            else {                                  // '+', '-', '*' or i == n
                if (sub.size() == n) {              // the whole expression is a number or variable
                    if (eval.count(sub)) {
                        return {{{}, eval[sub]}};   // variable is found in eval list 
                    }
                    if (isdigit(sub[0])) {
                        return {{{}, stoi(sub)}};   // number
                    }
                    return {{{sub}, 1}};            // variable
                }
                map<vector<string>, int, cmp> mult, submp = helper(sub, eval);
                for (auto l : local) {              // multiply local with sub
                    for (auto r : submp) {
                        auto k = l.first;
                        k.insert(k.end(), r.first.begin(), r.first.end());
                        sort(k.begin(), k.end());
                        mult[k] += l.second * r.second;
                    }
                }
                local = move(mult);
                if (i == n || expr[i] != '*') {     // '+' or '-'
                    for (auto& t : local) {         // add local to global
                        global[t.first] += sign * t.second;
                    }
                    sign = i < n && expr[i] == '-' ? -1 : 1;
                    local = {{{}, 1}};              // reset local
                }
                sub = "";                           // reset sub
            }
        }
        return global;
    }
};


leetcode 770 Basic Calculator IV题目解析 func basicCalculatorIV(expression string, evalvars []string, evalints []int) []string { index=0 //must have else commit alwalys fail however exe is right fmt.Println(expression) var res []string str = expression gEvalvars = evalvars gEvalints . 阅读详情

相关推荐

瑞芯微RK3506开发板DSM音频开发避坑指南:从硬件改接到内核配置全流程

本文详细解析了在瑞芯微RK3506开发板上进行DSM音频开发的完整流程与关键避坑点。内容涵盖从硬件改造(如电阻焊接)、内核驱动配置(DTS参数、补丁应用)到系统调试与波形分析的全过程,旨在帮助嵌入式开发者高效实现高信噪比、低成本的音频方案,避免常见错误。

weixin_29164091的博客 407

leetcode | go | 第770题 | 基本计算器Ⅳ

基本计算器Ⅳ

iCling的博客 554

OnePlus线刷救砖与OTA全量包:从故障恢复到系统升级的完整指南

本文详细介绍了OnePlus手机线刷救砖与OTA全量包的完整操作指南,包括故障诊断、线刷救砖实战教程、OTA全量包升级优势及进阶玩法。通过具体案例和实用技巧,帮助用户从系统故障恢复到安全升级,特别适合Android系统爱好者和OnePlus用户。

weixin_30338481的博客 616

LeetCode 770. Basic Calculator IV题目解析

转载源:戳这里题目解析此题是LeetCode 772的加强版,我们依然使用递归下降法来解决这个问题,文法如下:exp := exp +|- additive | additiveadditive := additive * factor | additivefactor := num | (exp) | variable(变量)我们使用vector&lt;string&gt;类型来表示表达式的结果...

cqx5555的博客 1710

基于Multisim的智能交通灯控制系统仿真与实现(含动态闪烁功能)

本文详细介绍了基于Multisim的智能交通灯控制系统仿真与实现,重点解析了动态闪烁功能的电路设计。通过555定时器、74LS192计数器和JK触发器等核心模块,实现了主干道与支干道的交替通行及黄灯1Hz闪烁功能,为交通灯控制系统设计提供了完整的仿真方案。

weixin_29174013的博客 425

STM32F103C8T6全桥逆变电路PWM波生成(基于HAL库)

全桥逆变电路需要两组开关管相互协同工作,故需要两路PWM控制信号,为了防止电源短路,需要保证同一桥臂的上下两个开关管不会同时导通,故两路PWM在相位上需要相差180°;为了保证高频变压器不会磁饱和,使正负半周PWM占空比相同。但是传统的互补输出达不到调节占空比调节输出电压的效果。......

weixin_45042735的博客 6022

LeetCode 每日一题767. 重构字符串

767. 重构字符串 给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。 若可行,输出任意可行的结果。若不可行,返回空字符串。 示例 1: 输入: S = "aab" 输出: "aba" 示例 2: 输入: S = "aaab" 输出: "" 注意: S 只包含小写字母并且长度在[1, 500]区间内。 解题思路: 先思考不能重构的情况,当有一个字母的次数大于整个字符串的一半,即 maxCount > (S.length() + 1) / 2。反之,字符串可以重构。 可以重

雷震子的博客 683

D457深度相机调试记录(max96712+max9295A)

使用max96712解串器解4路D457相机。采集深度相机Depth和RGB流。

navy2015_163的博客 1263

LeetCode //C - 770. Basic Calculator IV

This problem involves evaluating and simplifying algebraic expressions with variables. The solution requires parsing the expression, handling operator precedence, substituting variable values, combining like terms, and formatting the output according to sp

Made in Code 810

智能 Agent 跨模态决策机制实战:多源数据融合与感知驱动行为策略设计

随着智能 Agent 应用从结构化文本处理拓展至图像识别、语音交互、传感器响应等多模态环境,其决策机制也面临从单模态语言理解向“多源感知驱动行为选择”的系统跃迁。本文聚焦跨模态输入下的 Agent 决策体系,系统性解析多源数据建模、感知融合方式、模态对齐机制、输入权重控制策略与策略引擎适配路径,进一步结合多模态提示构建、模态感知异常检测、模态优先级路由调度等工程问题进行实战拆解。通过企业级智能客服、制造车间控制、智慧医疗助手等典型案例,本文提供面向真实场景的跨模态 Agent 架构与多输入决策融合方案。

努力分享一些人工智能、计算机视觉、影像等相关的知识干货! 1353

基于 Simulink 的固态变压器(SST)多级协同控制实战教程

《固态变压器多级协同控制仿真指南》摘要: 本教程详细讲解了基于Simulink的固态变压器(SST)三级架构建模与控制方法。核心内容包含:1)搭建级联H桥整流(CHB)、双有源桥(DAB)和逆变器(VSI)的三级主电路;2)提出创新的多级协同控制策略,通过功率前馈实现输入输出级动态匹配;3)给出系统级功率平衡、单元级均压控制的具体实现方案。教程特别强调解决实际工程中的关键问题:代数环处理、软启动设计和刚性系统求解器选择,并提供了硬件在环(HIL)仿真建议。附带的MATLAB代码示例可直接用于实现电容电压均衡

xiaoheshang_123的博客 117

Calculator系列问题四 LeetCode 770. Basic Calculator IV

LeetCode 770. Basic Calculator IV Given an expression such as expression = “e + 8 - a + 5” and an evaluation map such as {“e”: 1} (given in terms of evalvars = [“e”] and evalints = [1]), return a list...

katrina95的博客 695

基于Python的船舶AIS数据爬取与分析:从数据采集到可视化实战

本文详细介绍了如何使用Python构建一个完整的船舶AIS数据爬取与分析系统。文章从AIS系统的基本原理讲起,逐步深入到数据采集、存储、清洗、分析和可视化的全流程。我们将使用最新的Python技术栈,包括aiohttp异步爬虫、MongoDB存储、Pandas数据处理以及Pydeck三维可视化等。本文提供了完整的代码实现,并探讨了在实际应用中可能遇到的问题及其解决方案。关键词:AIS数据、Python爬虫、异步IO、数据可视化、海事分析。

2201_76125261的博客 811

leetcode 困难题 770. Basic Calculator IV 基本计算器 IV

加法数字单独考虑,两个多项式,若都是数字直接累加,若都是变量则提取出系数和字符串,系数累加的,若是没找到匹配的,就是累加到数字或者放入结果列表中,若是数字!=0则放入列表乘法数字单独考虑,若都是变量则提取出系数和字符串,系数累加的,字符串根据字典序排列并用*号拼接起来,若一个变量一个数字则系数累乘的而且字符串不变,还需要考虑结果列表中有相同字符串的结果,此时需要合并起来也就是系数累加起来,若是没找到匹配的,就是累加到数字或者放入结果列表中,若是数字!=0则放入列表还需要考虑结果是0的情况,此时也放入列表中当

邹九的个人博客 749

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

leetcode770. Basic Calculator IV

此题真可谓是练习编程语言的绝好材料 ! import java.util.*; class Solution { class Item { Map<String, Integer> vars = new TreeMap<>(); int k = 1; String tos() { StringBuilder build...

219

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

【Leetcode】770. Basic Calculator IV 基本计算器 IV

解法 跟编译原理相关的解释在这里 几个坑: 记得合并同类项 记得去掉系数为0的项 次数相同的项字典序较小的在前面 解法一:自顶向下 这里要注意,由于我们把语法改成非左递归了,但是减号是左结合的,所以要把term的值传给下一个expr让它计算 class Solution(object): def basicCalculatorIV(self, exp, evalvars, eva...

lemonmillie的博客 982

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

【Leetcode】770. Basic Calculator IV

这里不过是把数的计算变成了多项式的计算。我们需要先开一个多项式的“项”的结构体,那么多项式就是这个项的一个vector。然后还需要写好多项式的加法和乘法。其余思路和普通表达式一样。里的变量,用对应的整数值替换,然后对表达式进行化简,最后以。时空复杂度为表达式加上变量总长度。给定一个字符串形式的表达式。排序规则(返回数组的顺序)你需要将表达式中出现在。

数学、算法爱好者的博客 180

[Swift]LeetCode770. 基本计算器 IV | Basic Calculator IV

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★➤微信公众号:山青咏芝(shanqingyongzhi)➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)➤GitHub地址:https://github.com/strengthen/LeetCode➤原文地址:https://www.cnblogs.com/stren...

weixin_30413739的博客 240

Java实现 LeetCode 770 基本计算器 IV(暴力+分析题)

770. 基本计算器 IV 给定一个表达式 expression 如 expression = “e + 8 - a + 5...

Marcus 3419

[LeetCode] Basic Calculator IV 基本计算器之四

  Given an expression such as expression = "e + 8 - a + 5" and an evaluation map such as {"e": 1}(given in terms of evalvars = ["e"] and evalints = [1]), return a list of tokens representing the simp...

weixin_33971205的博客 312

leetcode_problem_rating用户完全指南:关键词搜索、评分区间过滤与自定义排序4大核心功能详解

📊 leetcode_problem_rating 是一个基于 **Elo 评分系统**为 LeetCode 周赛/双周赛题目计算难度分数的开源 Web 工具。它能帮你快速找到"某分数段"、"某场竞赛"、"某关键词"下的题目,适合刷题选手精准选题。本文带你用 10 分钟掌握它的 4 大核心功能。 --- ## 项目简介:它是什么? 这个项目的前端界面会把 LeetCode 历次周赛(Wee

gitblog_00649的博客 830

LeetCode 767. 重构字符串(堆)

文章目录1. 题目2. 解题 1. 题目 给定一个字符串S,检查是否能重新排布其中的字母,使得两相邻的字符不同。 若可行,输出任意可行的结果。若不可行,返回空字符串。 示例 1: 输入: S = "aab" 输出: "aba" 示例 2: 输入: S = "aaab" 输出: "" 注意: S 只包含小写字母并且长度在[1, 500]区间内。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reorganize-string 著作权归领扣网络所

Michael是个半路程序员 2342

LeetCode770之基本计算器IV(相关话题:波兰表达式,多项式运算)

这题是波兰表达式,多项式运算的综合运用

数据与算法架构提升之路专栏 726

leetcode | go | 第767题 | 重构字符串

【代码】leetcode | go | 第767题 | 重构字符串。

iCling的博客 497
上一篇: [Leetcode] 769. Max Chunks To Make Sorted 解题报告
下一篇: [Leetcode] 771. Jewels and Stones 解题报告
魔豆Magicbean
博客等级 码龄19年 146粉丝 742原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值