-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path306. Additive Number.java
More file actions
36 lines (33 loc) · 1.09 KB
/
306. Additive Number.java
File metadata and controls
36 lines (33 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class Solution {
public boolean isAdditiveNumber(String num) {
int len = num.length();
if (len == 0) {
return true;
}
for (int i = 1; i <= len/2; i++) {
String strPrev = num.substring(0, i);
if (strPrev.length() > 1 && strPrev.startsWith("0")) {
continue;
}
for (int j = i + 1; j < len; j++) {
String strPost = num.substring(i, j);
if (strPost.length() > 1 && strPost.startsWith("0")) {
continue;
}
if (dfs(num.substring(j), Long.valueOf(strPrev), Long.valueOf(strPost))) {
return true;
}
}
}
return false;
}
public boolean dfs(String str, long prev, long post) {
if (str.length() == 0) {
return true;
}
if (str.startsWith(String.valueOf(prev + post))) {
return dfs(str.substring(String.valueOf(prev + post).length()), post, prev + post);
}
return false;
}
}