原题链接:306. Additive Number
【思路】
public boolean isAdditiveNumber(String num) {
for (int i = 1; i <= num.length() / 2; i++)
for (int j = 1; j + i < num.length(); j++)
if (isValid(num, num.substring(0, i), num.substring(i, i + j), i + j)) return true;
return false;
}
public boolean isValid(String num, String first, String second, int index) {
if (first.length() > 1 && first.startsWith("0")
|| second.length() > 1 && second.startsWith("0")) return false;
if (index == num.length()) return true;
long sum = Long.parseLong(first) + Long.parseLong(second);
if (num.startsWith(sum + "", index))
if(isValid(num, second, sum + "", index + (sum + "").length())) return true;
return false;
}
37 / 37
test cases passed. Runtime: 3 ms Your runtime beats 29.26% of javasubmissions.