当前位置:网站首页>592. 分数加减运算 : 表达式计算入门题
592. 分数加减运算 : 表达式计算入门题
2022-07-27 12:33:00 【宫水三叶的刷题日记】
题目描述
这是 LeetCode 上的 592. 分数加减运算 ,难度为 中等。
Tag : 「表达式计算」、「模拟」
给定一个表示分数加减运算的字符串 expression,你需要返回一个字符串形式的计算结果。
这个结果应该是不可约分的分数,即最简分数。 如果最终结果是一个整数,例如 ,你需要将它转换成分数形式,其分母为 。所以在上述例子中, 应该被转换为 2/1。
示例 1:
输入: expression = "-1/2+1/2"
输出: "0/1"
示例 2:
输入: expression = "-1/2+1/2+1/3"
输出: "1/3"
示例 3:
输入: expression = "1/3-1/2"
输出: "-1/6"
提示:
输入和输出字符串只包含 '0'到'9'的数字,以及'/','+'和'-'。输入和输出分数格式均为 ±分子/分母。如果输入的第一个分数或者输出的分数是正数,则'+'会被省略掉。输入只包含合法的最简分数,每个分数的分子与分母的范围是 。 如果分母是 ,意味着这个分数实际上是一个整数。 输入的分数个数范围是 。 最终结果的分子与分母保证是 位整数范围内的有效整数。
表达式计算
为了方便,令 expression 为 s。
由于给定的表达式中只有 + 和 -,因此无须考虑优先级问题,直接从前往后计算即可。
使用变量 ans 代指计算过程中的结果,从前往后处理表达式 s,每次以 ±分子/分母 的形式取出当前操作数(若为表达式的首个操作数,且为正数时,需要手动补一个 +)。
假设当前取出的操作数为 num,根据 ans 的情况进行运算:
若 ans为空串,说明num是首个操作数,直接将num赋值给ans即可若 ans不为空串,此时计算num和ans的计算结果赋值给ans
考虑实现一个计算函数 String calc(String a, String b) 计算两个操作 a 和 b 的结果,其中入参 a 和 b 以及返回值均满足 ±分子/分母 形式。
首先通过读取 a 和 b 的首个字符,得到两操作数的正负情况。若为一正一负,通过交换的形式,确保 a 为正数,b 为负数。
然后通过 parse 方法拆解出字符串操作数的分子和分母,parse 使用指针扫描的方式实现即可,以数组形式将结果返回(第 位为分子数值,第 位分母数值)。
假设操作数 a 对应的值为 ,操作数的值为 ,先将其转换为 和 ,进行运算后,再通过求最大公约数 gcd 的方式进行化简。
Java 代码:
class Solution {
public String fractionAddition(String s) {
int n = s.length();
char[] cs = s.toCharArray();
String ans = "";
for (int i = 0; i < n; ) {
int j = i + 1;
while (j < n && cs[j] != '+' && cs[j] != '-') j++;
String num = s.substring(i, j);
if (cs[i] != '+' && cs[i] != '-') num = "+" + num;
if (!ans.equals("")) ans = calc(num, ans);
else ans = num;
i = j;
}
return ans.charAt(0) == '+' ? ans.substring(1) : ans;
}
String calc(String a, String b) {
boolean fa = a.charAt(0) == '+', fb = b.charAt(0) == '+';
if (!fa && fb) return calc(b, a);
long[] p = parse(a), q = parse(b);
long p1 = p[0] * q[1], q1 = q[0] * p[1];
if (fa && fb) {
long r1 = p1 + q1, r2 = p[1] * q[1], c = gcd(r1, r2);
return "+" + (r1 / c) + "/" + (r2 / c);
} else if (!fa && !fb) {
long r1 = p1 + q1, r2 = p[1] * q[1], c = gcd(r1, r2);
return "-" + (r1 / c) + "/" + (r2 / c);
} else {
long r1 = p1 - q1, r2 = p[1] * q[1], c = gcd(Math.abs(r1), r2);
String ans = (r1 / c) + "/" + (r2 / c);
if (p1 >= q1) ans = "+" + ans;
return ans;
}
}
long[] parse(String s) {
int n = s.length(), idx = 1;
while (idx < n && s.charAt(idx) != '/') idx++;
long a = Long.parseLong(s.substring(1, idx)), b = Long.parseLong(s.substring(idx + 1));
return new long[]{a, b};
}
long gcd(long a, long b) {
return b == 0 ? a : gcd(b, a % b);
}
}
TypeScript 代码:
function fractionAddition(s: string): string {
const n = s.length
let ans = ""
for (let i = 0; i < n; ) {
let j = i + 1
while (j < n && s[j] != '+' && s[j] != '-') j++
let num = s.substring(i, j)
if (s[i] != '+' && s[i] != '-') num = "+" + num
if (ans != "") ans = calc(num, ans)
else ans = num
i = j
}
return ans[0] == "+" ? ans.substring(1) : ans
};
function calc(a: string, b: string): string {
const fa = a[0] == "+", fb = b[0] == "+"
if (!fa && fb) return calc(b, a)
const p = parse(a), q = parse(b)
const p1 = p[0] * q[1], q1 = q[0] * p[1]
if (fa && fb) {
const r1 = p1 + q1, r2 = p[1] * q[1], c = gcd(r1, r2)
return "+" + (r1 / c) + "/" + (r2 / c)
} else if (!fa && !fb) {
const r1 = p1 + q1, r2 = p[1] * q[1], c = gcd(r1, r2)
return "-" + (r1 / c) + "/" + (r2 / c)
} else {
const r1 = p1 - q1, r2 = p[1] * q[1], c = gcd(Math.abs(r1), r2)
let ans = (r1 / c) + "/" + (r2 / c)
if (p1 > q1) ans = "+" + ans
return ans
}
}
function parse(s: string): number[] {
let n = s.length, idx = 1
while (idx < n && s[idx] != "/") idx++
const a = Number(s.substring(1, idx)), b = Number(s.substring(idx + 1))
return [a, b]
}
function gcd(a: number, b: number): number {
return b == 0 ? a : gcd(b, a % b)
}
时间复杂度: 空间复杂度:
加餐 & 加练
加餐一道更贴合笔试面试的「表达式计算」问题 : 双栈 : 表达式计算问题的通用解法
最后
这是我们「刷穿 LeetCode」系列文章的第 No.592 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。
在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。
为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode 。
在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。
更多更全更热门的「笔试/面试」相关资料可访问排版精美的 合集新基地
边栏推荐
- Why does MySQL index use b+ tree instead of jump table?
- 详述反射中构造方法、属性和普通方法
- Plus版SBOM:流水线物料清单PBOM
- 5V boost 9V chip
- Detailed explanation of flask framework
- SSM实战项目-前后分离(简单易懂)
- Complete data summary of lapsus$apt organization that stole Microsoft's source code in March 2022
- Top of the tide - reading notes + excerpts + insights
- Data Lake (20): Flink is compatible with iceberg, which is currently insufficient, and iceberg is compared with Hudi
- Top 10 international NFT exchanges
猜你喜欢

Julia beginner tutorial 2022

5V boost 9V chip

Solution: the idea project does not display a tree view
Ali II: what if the AOF file in redis is too large?

JVM memory layout detailed, illustrated, well written!

MySQL扩展

Will MySQL fail to insert data? Why?

20210519 leetcode double pointer

评价自动化测试优劣的隐性指标
QT | qcheckbox of control
随机推荐
20210419 combined sum
详述HashSet的add方法
Security measures for tcp/ip protocol vulnerabilities
正则表达式去除两端空格
POJ1988_ Cube Stacking
Enjoy the luxury meta universe louis:the game, and participate in the NFT series digital collection white roll activity | tutorial
Plus版SBOM:流水线物料清单PBOM
BSP video tutorial issue 21: easy one key implementation of serial port DMA variable length transceiver, support bare metal and RTOS, including MDK and IAR, which is more convenient than stm32cubemx (
String to realize fuzzy query
关于 CMS 垃圾回收器,你真的懂了吗?
Good looking (dynamic) Jay fan self-made dynamic album card (front and back are different) and lyrics page
Detailed explanation of flask framework
BSP视频教程第21期:轻松一键实现串口DMA不定长收发,支持裸机和RTOS,含MDK和IAR两种玩法,比STM32CubeMX还方便(2022-07-24)
Solution: can not issue executeupdate() or executelargeupdate() for selections
评价自动化测试优劣的隐性指标
SparkSubmit.main()方法提交外部参数,远程提交standalone集群任务
Redistemplate cannot get the value according to the key
详述try-catch-finally
Recursive method | Fibonacci sequence
C program debugging and exception handling (try catch)