import
java.util.*;
public
class
GFG {
static
class
StringLengthComparator
implements
Comparator<String> {
@Override
public
int
compare(String a, String b) {
return
Integer.compare(a.length(), b.length());
}
}
public
static
int
longestStringChain(List<String> words) {
words.sort(
new
StringLengthComparator());
Map<String, Integer> chainLengths =
new
HashMap<>();
int
result =
1
;
for
(String word : words) {
chainLengths.put(word,
1
);
for
(
int
j =
0
; j < word.length(); j++) {
StringBuilder copyCurrentWord =
new
StringBuilder(word);
copyCurrentWord.deleteCharAt(j);
String temp = copyCurrentWord.toString();
if
(chainLengths.containsKey(temp)) {
chainLengths.put(word, Math.max(chainLengths.get(temp) +
1
, chainLengths.get(word)));
result = Math.max(result, chainLengths.get(word));
}
}
}
return
result;
}
public
static
void
main(String[] args) {
List<String> words = Arrays.asList(
"a"
,
"b"
,
"ba"
,
"bca"
,
"bda"
,
"bdca"
);
System.out.println(longestStringChain(words));
}
}