LeetCode 139. Word Break 单词拆分

题目

https://leetcode.com/problems/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.

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

讲解

题目是求一个字符串s是否能切分出所有wordDict里面的单词。

本题的动态规划状态变量isWordBreak[i]: 表示s的前i个位置能否切分出wordDict里面的单词。初始化时,isWordBreak[0]为true,表示空字符串””也是在wordDict里的单词。

二重循环,j < i,用来计算s字符串第 i 位置能否切出wordDict里面的单词。

  • f[j] 用来获取s的前 j 个位置是否能切出wordDict里面的单词。
  • 只有当isWordBreak[j] = true(即s前 j 个字符能切出单词)并且s.substring(j, i) 也是在wordDict里面单词的时候,表明s的第 i 位置可以切分。

视频教学

Java参考代码

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] isWordBreak = new boolean[s.length() + 1];
        
        isWordBreak[0] = true;
        
        for (int i = 0; i < s.length() + 1; i++) {
            for (int j = 0; j < i; j++) {
                if (!isWordBreak[j]) {
                    continue;
                }
                
                if (wordDict.contains(s.substring(j, i))) {
                    isWordBreak[i] = true;
                    break;
                }
            }
        }
        
        return isWordBreak[s.length()];
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注