Skip to content

Commit 9eb5b5a

Browse files
authored
Create Solution.java
1 parent 3fa84e1 commit 9eb5b5a

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
class Solution {
2+
public int longestStrChain(String[] words) {
3+
Arrays.sort(words, new Comparator<String>() {
4+
@Override
5+
public int compare(String o1, String o2) {
6+
return Integer.compare(o1.length(), o2.length());
7+
}
8+
});
9+
int res = 0;
10+
Map<String, Integer> map = new HashMap<>();
11+
for (String word : words) {
12+
int x = 1;
13+
for (int i = 0; i < word.length(); ++i) {
14+
String pre = word.substring(0, i) + word.substring(i + 1);
15+
x = Math.max(x, map.getOrDefault(pre, 0) + 1);
16+
}
17+
map.put(word, x);
18+
res = Math.max(res, x);
19+
}
20+
return res;
21+
}
22+
}

0 commit comments

Comments
 (0)