Skip to content

Instantly share code, notes, and snippets.

@vrat28
Created May 17, 2021 17:48
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/3a0de4ba1586a7766fa34edb53f9cdeb to your computer and use it in GitHub Desktop.
Save vrat28/3a0de4ba1586a7766fa34edb53f9cdeb to your computer and use it in GitHub Desktop.
Longest String Chain (Top Down)
class Solution {
func longestStrChain(_ words: [String]) -> Int {
guard words.count > 1 else { return words.count }
var map = [String:Int]()
var maxLength = 0
let wordSet = Set(words)
for word in wordSet{
let chainLength = dfs(wordSet, &map, word)
maxLength = max(chainLength, maxLength)
}
return maxLength
}
func dfs(_ words:Set<String>, _ map :inout [String:Int], _ str:String) -> Int {
if let cachedLength = map[str] {
return cachedLength
}
var maxLength = 1
for i in 0..<str.count{
var word = str
let index = word.index(word.startIndex,offsetBy: i)
word.remove(at:index)
if words.contains(word){
let currentLength = 1 + dfs(words,&map, word)
maxLength = max(maxLength, currentLength)
}
}
map[str] = maxLength
return maxLength
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment