Created
May 17, 2021 15:42
-
-
Save vrat28/a3d25d53912f0f1860dbbbca3454ed6a to your computer and use it in GitHub Desktop.
Longest String Chain (Dynamic Programming)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func longestStrChain(_ words: [String]) -> Int { | |
guard words.count > 1 else { return words.count} | |
let words = words.sorted(by: { word1, word2 in | |
return word1.count < word2.count | |
}) | |
var map = [String:Int]() | |
var maxLength = 0 | |
for word in words{ | |
var currentMax = 1 | |
for j in 0..<word.count { | |
var wordCopy = word | |
wordCopy.remove(at: word.index(word.startIndex, offsetBy:j)) | |
if let existingLength = map[wordCopy] { | |
currentMax = max(currentMax, existingLength + 1) | |
} | |
} | |
map[word] = currentMax | |
maxLength = max(maxLength, currentMax) | |
} | |
return maxLength | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment