forked from yehongzhi/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
[1048]最长字符串链.java
35 lines (33 loc) · 975 Bytes
/
[1048]最长字符串链.java
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
class Solution {
public int longestStrChain(String[] words) {
Arrays.sort(words, Comparator.comparingInt(String::length));
int[] dp = new int[words.length];
int ans = 0;
for (int i = 1; i < words.length; i++) {
for (int j = 0; j < i; j++) {
if (contain(words[i], words[j])) {
dp[i] = Math.max(dp[i], dp[j] + 1);
ans = Math.max(dp[i], ans);
}
}
}
return ans + 1;
}
//判断s2是否为s1的前身
private boolean contain(String s1, String s2) {
if (s1.length() != s2.length() + 1) {
return false;
}
int i = 0;
int j = 0;
while (i < s1.length() && j < s2.length()) {
if (s1.charAt(i) == s2.charAt(j)) {
i++;
j++;
} else {
i++;
}
}
return j == s2.length();
}
}