func longestStrChain(_ words: [String]) -> Int {
let words = words.sorted { $0.count < $1.count }
var dp = Array(repeating: 1, count: words.count)
var answer = 1
for i in stride(from: 1, to: words.count, by: 1) {
for j in stride(from: i-1, through: 0, by: -1) {
let diff = words[i].count - words[j].count
if diff == 0 {
continue
} else if diff > 1 {
break
} else {
if isFront(words[j], words[i]) {
dp[i] = max(dp[i], dp[j]+1)
}
answer = max(answer, dp[i])
}
}
}
return answer
}
private func isFront(_ previous: String, _ next: String) -> Bool {
var i = 0
var j = 0
var previous = Array(previous)
var next = Array(next)
while i < previous.count {
if previous[i] == next[j] {
i += 1
j += 1
} else {
j += 1
if j - i > 1 {
return false
}
}
}
return true
}
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme