leetcode笔记(word break)

 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

胡乱的想法

动态规划,假设到输入字符串到 0 到 [j] 区间是可以被字典中的词组成的,那么如果 [j]+1 到 [i] (i > j) 区间到子字符串存在于字典中,那么 0 到 [i] 区间也可以被字典中到词组成。为了判断到字符串中某个位置 [i] 之前的部分是否可以被字典构成,则可以通过判断 [i] 之前所有可以被字典构成的索引值到 [i] 位置的子字符串是否包含于字典中。


代码

class Solution {
public boolean wordBreak(String s, List<String> wordDict) {
    // 先判断直到字符串的某一个位置(开区间)是否可以由字典组成
    // 然后判断从这些位置到新位置到子串是否被字典包含
    Set<String> set = new HashSet<>();
    for(String word : wordDict) {
        set.add(word);
    }
    
    boolean[] dp = new boolean[s.length() + 1];
    dp[0] = true;
    for(int i = 0; i <= s.length(); i++) {
        for(int j = 0; j <= i; j++) {
            if(!dp[j]) continue;
            if(set.contains(s.substring(j, i))) {
                dp[i] = true;
                break;
            }
        }
    }
    return dp[s.length()];
}

参考资料

https://leetcode.com/problems/word-break/

评论

此博客中的热门博文

HashMap比较数字时用equals而不是==

HashMap思考题