Loading

[LeetCode] 139. Word Break(分割单词)

Description

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
给定一个非空字符串和一个包含非空单词的字典,判断这个字符串是否能够分割为字典中的单词(该字符串能否通过字典中的单词构成)。

Note

  • The same word in the dictionary may be reused multiple times in the segmentation.
    字典里的词可以重复使用
  • You may assume the dictionary does not contain duplicate words.
    你可以假定字典内没有重复的词

Examples

Example 1

Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".

Example 2

Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
             Note that you are allowed to reuse a dictionary word.

Example 3

Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false

Solution

这题的动态规划解法虽然能把时间复杂度降下来,但实际运行时间并不是很理想。

dp[i] 表示 s[0, i) 子串是否满足条件,问题转换为求解 dp[s.length]

明显地,dp[0] 应该是 true(我不用字典里的单词,造一个空串,当然可以咯)

那么 dp[i] 要怎么确定,这就和字典中的单词有关了。记字典中的单词为 word,那么 dp[i]true 当且仅当:

  • s[i - word.length, i) 子串为 word

  • dp[i - word.length]true

这就是本题的状态转移方程,代码如下:

class Solution {
    fun wordBreak(s: String, wordDict: List<String>): Boolean {
        val wordSet = wordDict.toSet()
        val dp = BooleanArray(s.length + 1)
        dp[0] = true

        for (i in 1..s.length) {
            for (j in 0 until i) {
                if (dp[j] && s.substring(j, i) in wordSet) {
                    dp[i] = true
                    break
                }
            }
        }

        return dp.last()
    }
}
posted @ 2020-11-30 11:46  Zhongju.copy()  阅读(79)  评论(0编辑  收藏  举报