leetcode-complex number multiplication
2017-07-19 10:46
369 查看
正则表达式的使用
对参考答案的学习
1.通过正则表达式提取需要的内容
下面代码就将一个负数a+bi中的数字a和b提取出来,从而拿来参与运算。Pattern pattern=Pattern.compile("([-]?[0-9]+)(\\+)([-]?[0-9]+)(i)"); Matcher matcher=pattern.matcher(string); while(matcher.find()){ a1=Integer.parseInt(matchera.group(1)); b1=Integer.parseInt(matchera.group(3)); }
菜鸟教程-正则表达式语法
2.”([-]?[0-9]+)(\+)([-]?[0-9]+)(i)”
()用来记录子表达式;即([-]?[0-9]+) 、 (\+) 、 ([-]?[0-9]+) 、 (i)分别是四个子表达式group(0)是整个表达式
group(1) group(2) group(3) group(4)分别是上述四个表达式
[-]?[0-9]+ 表示负数
3.别人的做法
public class Solution { public String complexNumberMultiply(String a, String b) { String x[] = a.split("\\+|i"); String y[] = b.split("\\+|i"); int a_real = Integer.parseInt(x[0]); int a_img = Integer.parseInt(x[1]); int b_real = Integer.parseInt(y[0]); int b_img = Integer.parseInt(y[1]); return (a_real * b_real - a_img * b_img) + "+" + (a_real * b_img + a_img * b_real) + "i"; } }
机智的别人的做法,学习一些split函数:
split
public String[] split(String regex)
Splits this string around matches of the given regular expression.
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
regex是语法;
使用时需注意:
a.如遇特殊字符,需加”\”转义
b.如需要多个分割符,需用“|”连接不同的分隔符
详解见
http://www.cnblogs.com/liubiqu/archive/2008/08/14/1267867.html
相关文章推荐
- LeetCode - Complex Number Multiplication
- [LeetCode] Complex Number Multiplication 复数相乘
- [LeetCode-Algorithms-537] "Complex Number Multiplication" (2017.12.7-WEEK14)
- [leetcode]-537 Complex Number Multiplication
- leetcode537: Complex Number Multiplication
- leetcode 537 Complex Number Multiplication(Medium)
- [Leetcode] #537 Complex Number Multiplication(stringstream)
- lintcode/leetcode由易至难第22题:Complex Number Multiplication
- LeetCode Complex Number Multiplication
- [LeetCode] Kth Smallest Number in Multiplication Table 乘法表中的第K小的数字
- Complex Number Multiplication
- Complex Number Multiplication
- Complex Number Multiplication
- [leetcode] 668 Kth Smallest Number in Multiplication Table
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- LeetCode 668: Kth Smallest Number in Multiplication Table
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication
- 537. Complex Number Multiplication