Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 17, 2021 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrat28/a3d25d53912f0f1860dbbbca3454ed6a to your computer and use it in GitHub Desktop.
Save vrat28/a3d25d53912f0f1860dbbbca3454ed6a to your computer and use it in GitHub Desktop.
Longest String Chain (Dynamic Programming)
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