关闭

Middle-题目90:306. Additive Number

85人阅读 评论(0) 收藏 举报
分类:

题目原文:
Additive number is a string whose digits can form additive sequence.

A valid additive sequence should contain at least three numbers. Except for the first two numbers, each subsequent number in the sequence must be the sum of the preceding two.

For example:
“112358” is an additive number because the digits can form an additive sequence: 1, 1, 2, 3, 5, 8.

1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
“199100199” is also an additive number, the additive sequence is: 1, 99, 100, 199.
1 + 99 = 100, 99 + 100 = 199
Note: Numbers in the additive sequence cannot have leading zeros, so sequence 1, 2, 03 or 1, 02, 3 is invalid.

Given a string containing only digits ‘0’-‘9’, write a function to determine if it’s an additive number.
题目大意:
判断一个由’0’-‘9’组成的字符串是不是” Additive Number”.
Additive Number 的定义是,可以拆成至少3个子串,其中任意前两个子串对应数字的和都等于后一个子串。
例如“112358”、“199100199”都是Additive Number。
需要注意的是,Additive Number中拆出的子串不能是以0开头的,例如”1023”不是Additive Number,因为拆成”1”,”02”,”3”不是合法的。
题目分析:
用的是暴力的解法,因为考虑Additive Number拆出的子串有可能非常长,故使用BigInteger存储(但是看别人的ac代码好像用的是long,这严格意义上说是不严谨的),从第一个数字开始暴力枚举,拆出前两个数并求和,再转换成字符串,看看拆掉前两个数后的子串是不是以这个“和字符串”开头,如果是,则减掉第一个数继续判断。以此类推直到找不到这样三个子串,或者拆掉前两个数的子串恰好等于“和字符串”。
源码:(language:java)

import java.math.BigInteger;

public class Solution {
    public boolean isAdditiveNumber(String num) {
        int length = num.length();
        boolean result = false;
        for(int i = 0;i<length-1;i++){
            //if(num.charAt(i+1)=='0')
            //  continue;
            String temp1 = num.substring(0, i+1);
            if(temp1.length() > 1 && temp1.startsWith("0"))
                continue;
            BigInteger num1 = new BigInteger(num.substring(0, i+1)); // start: 0 ,end: i
            for(int j= i+1;j<length-1;j++) {
                String temp2 = num.substring(i+1,j+1);
                if(temp2.length()>1 && temp2.startsWith("0"))
                    break;
                BigInteger num2 = new BigInteger(num.substring(i+1,j+1));
                BigInteger sum = num1.add(num2);
                if(num.length()-j-1<sum.toString().length())
                    break;
                else if(num.substring(j+1, j+1+sum.toString().length()).equals(sum.toString())) {
                    if(1+j+sum.toString().length() == num.length()) {
                        result= true;
                        break;
                    }
                    else    
                        result = result || isAdditiveNumber(num.substring(i+1));
                }
            }
        }
        return result;
    }
}

成绩:
23ms,beats 1.60%,众数3ms,39.48%
Cmershen的碎碎念:
本题成绩较差,感觉是由于BigInteger拖慢了时间,看了其他的ac代码,有的是用long(这是不严谨的),有的是直接底层实现了高精度加法。

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:55583次
    • 积分:3194
    • 等级:
    • 排名:第10669名
    • 原创:270篇
    • 转载:53篇
    • 译文:0篇
    • 评论:7条
    文章分类
    最新评论