【LeetCode】537. Complex Number Multiplication
1.题目
Given two strings representing two complex numbers.
You need to return a string representing their multiplication. Note i2 = -1 according to the definition.
Example 1:
Input: "1+1i", "1+1i"
Output: "0+2i"
Explanation: (1 + i) * (1 + i) = 1 + i2 + 2 * i = 2i, and you need convert it to the form of 0+2i.
Example 2:
Input: "1+-1i", "1+-1i"
Output: "0+-2i"
Explanation: (1 - i) * (1 - i) = 1 + i2 - 2 * i = -2i, and you need convert it to the form of 0+-2i.
Note:
The input strings will not have extra blank.
The input strings will be given in the form of a+bi, where the integer a and b will both belong to the range of [-100, 100]. And the output should be also in this form.
2.思考点
这道题不难,只要将数学表达式展开然后拆解字符串就可以了。
public String complexNumberMultiply(String a, String b) {
String string = a.split("\\+")[0];
int num1 = Integer.valueOf(a.split("\\+")[0]);
int num2 = Integer.valueOf(a.split("\\+")[1].substring(0,a.split("\\+")[1].length()-1));
int num3 = Integer.valueOf(b.split("\\+")[0]);
int num4 = Integer.valueOf(b.split("\\+")[1].substring(0,b.split("\\+")[1].length()-1));
return (num1*num3 + num2*num4*(-1)) + "+" + (num2*num3 + num1*num4) + "i";
}
这个是我最开始的解法,用加号来拆解字符串,然后用substring将i拆解出来。然后在我看solution时发现正则表达式中的“|”代表或,那么这里就有另一种方法
public String complexNumberMultiply(String a, String b) {
String string = a.split("\\+|i")[0];
int num1 = Integer.valueOf(a.split("\\+|i")[0]);
int num2 = Integer.valueOf(a.split("\\+|i")[1]);
int num3 = Integer.valueOf(b.split("\\+|i")[0]);
int num4 = Integer.valueOf(b.split("\\+|i")[1]);
return (num1*num3 + num2*num4*(-1)) + "+" + (num2*num3 + num1*num4) + "i";
}
我们可以明显的发现,全部使用正则表达式来拆解字符串效率会低很多,接着大家可以参考这篇文章https://yq.aliyun.com/articles/292304。
我们可以发现,正则表达式实际效率是很低的,如果要进行普通的字符串操作,推荐使用Apache Commons Lang这个包。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器