【数学】B040_复数乘法(字符串处理 | 正则表达式)

一、题目描述

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 + 2i = 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 - 2i = -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.

二、题解

(1) 字符串分割(或 Regex 表达式)

  • 要注意:在 j a v a java \ 是特殊字符,需要再次使用 \ 进行转义。
  • 竖线 | 在正则中表达特殊字符 " " "或" 的意思
/**
 * @thought:
 * @date: 1/18/2020 7:01 PM
 * @Execution info:
 *  ·执行用时 2 ms 击败了 70.08% 的java用户
 *  ·内存消耗 MB 击败了 53.27% 的java用户
 * @Asymptotic Time Complexity:O()
 */
public String complexNumberMultiply(String a, String b) {
  String[] ab = a.split("\\+");   // 1
  String[] cd = b.split("\\+");
  String x[] = a.split("\\+|i");  // 2

  int ta = Integer.parseInt(ab[0]);
  int tb = Integer.parseInt(ab[1].split("i")[0]); // -1i -> -1
  int tc = Integer.parseInt(cd[0]);
  int td = Integer.parseInt(cd[1].split("i")[0]); // -1i -> -1

//    String real = ta*tc - tb*td == 0 ? "0" : (ta*tc - tb*td) + "";
//    String img = ta*td + tb*tc == 0 ? "0" : ta*td + tb*tc + "";
//    return real + "+"+ img +  "i";
  return ta*tc - tb*td + "+" + ta*td + tb*tc + "i";
}

复杂度分析

  • 时间复杂度: O ( 1 ) O(1) ,取决于 s p l i t ( S t r i n g s ) split(String s) 的参数 s s 的长度。根据题目中的 给出信息可得: 4 < s < 20 4 < s < 20
  • 空间复杂度: O ( 1 ) O(1)
发布了300 篇原创文章 · 获赞 48 · 访问量 8048

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/104034157
今日推荐