File tree 1 file changed +33
-0
lines changed
1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ //Time : NlogN + N * Length * Length
3
+ //Space : O(N*Length)
4
+ class Solution {
5
+ public int longestStrChain(String[] words) {
6
+ //Sort on length
7
+ //Time : NlogN
8
+ Arrays.sort(words, (a,b) -> a.length()-b.length());
9
+ int res = 0;
10
+ Map<String, Integer> memo = new HashMap<>();
11
+
12
+ //Iterate on the words
13
+ //TIme : N * Length * Length
14
+ for(String word : words) {
15
+ //Put current word in map with default value.
16
+ memo.put(word, 1);
17
+ //Time : Length * Length
18
+ for(int i = 0; i < word.length(); i++) {
19
+ StringBuilder current = new StringBuilder(word);
20
+ String next = current.deleteCharAt(i).toString(); //Time : Length
21
+ //Check if the value for next is already calculated
22
+ if(memo.containsKey(next)) {
23
+ //Update the value in map with the maximum possible value
24
+ memo.put(word, Math.max(memo.get(word), memo.get(next)+1));
25
+ }
26
+ }
27
+
28
+ res = Math.max(res, memo.get(word));
29
+ }
30
+
31
+ return res;
32
+ }
33
+ }
You can’t perform that action at this time.
0 commit comments