-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathLongest String Chain.java
40 lines (38 loc) · 1.17 KB
/
Longest String Chain.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
36
37
38
39
40
class Solution {
Boolean compareForIncreaseByOne(String str1,String str2){
//str 1 will be long than str2
int first=0;
int second=0;
if(str1.length() != (str2.length() + 1)){
return false;
}
while(first < str1.length()){
if(second < str2.length() && str1.charAt(first) == str2.charAt(second)){
first++;
second++;
}else{
first++;
}
}
if(first == str1.length() && second == str2.length()){
return true;
}
return false;
}
public int longestStrChain(String[] words) {
int N = words.length;
Arrays.sort(words,(a,b) -> a.length()-b.length()); //as Sequence/Subset are not ordered
int []dp =new int[N];
Arrays.fill(dp,1);
int maxi = 1;
for(int i=0;i<N;i++){
for(int j=0;j<i;j++){
if(compareForIncreaseByOne(words[i],words[j]) && dp[j]+1 > dp[i]){
dp[i] = dp[j] + 1;
maxi = Math.max(maxi,dp[i]);
}
}
}//for neds
return maxi;
}
}