0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode #1048: Longest String Chain

0
Posted at
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
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?