您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: