leetcode-complex number multiplication

正则表达式的使用

对参考答案的学习

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值