Created
May 17, 2021 17:48
-
-
Save vrat28/3a0de4ba1586a7766fa34edb53f9cdeb to your computer and use it in GitHub Desktop.
Longest String Chain (Top Down)
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 } | |
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