0
点赞
收藏
分享

微信扫一扫

#139 Word Break

you的日常 2022-02-28 阅读 67

Description

Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.

Note that the same word in the dictionary may be reused multiple times in the segmentation.

Examples

Example 1:

Example 2:

Note that you are allowed to reuse a dictionary word.

Example 3:

Constraints:

思路

  • 最开始的时候我理解错了题目意思,我以为要用到wordDict中的所有单词才算true,但其实是只要可以通过wordDict中的一个或几个单词组成s就可以达成true
  • 看到题目的时候我想到的就是递归,下面递归的代码有restWords和backUpWords就是因为最开始的理解错误,后面发现了错误只改了退出条件没有改中间流程,就保留下来了。
    • 具体的步骤就是依次判断当前字符串能不能由restWords+backUpWords中的单词组成

  • 但是递归算法会TLE,秉承着所有递归都能写成循环的理论,我想到了dp的方法,构建dp数组,这个数组的长度就是s的长度,数组为boolean类型,每个boolean表示能否用wordDict中的单词组成s.substring(0, current_position)
    • 状态转移方程:当前位置能否为 true 取决于 wordDict 中是否存在一个长度为length的word,使得 dp[current_position - length] = true 且 s.substring(current_position - length, current_position) = word

代码

递归代码

class Solution {
    public boolean canBreak(String s, List<String> restWords, List<String> backUpWords){
        if (s.length() == 0)
            return true;
        
        for (String word: restWords){
            if (s.indexOf(word) == 0){
                List<String> newRestWords = new ArrayList<>(restWords);
                List<String> newBackUpWords = new ArrayList<>(backUpWords);
                newRestWords.remove(word);
                newBackUpWords.add(word);
                if (canBreak(s.substring(word.length()), newRestWords, newBackUpWords))
                    return true;
            }
        }
        
        for (String word: backUpWords){
            if (s.indexOf(word) == 0){
                if (canBreak(s.substring(word.length()), restWords, backUpWords))
                    return true;
            }
        }
        
        return false;
        
    }
    public boolean wordBreak(String s, List<String> wordDict) {
        return canBreak(s, wordDict, new ArrayList<>());
    }
}

DP代码

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Boolean[] flag = new Boolean[s.length() + 1];
        flag[0] = true;
        for (int i = 1; i < s.length() + 1; i++)
            flag[i] = false;
        for (int i = 1; i < s.length() + 1; i++){
            for (String word: wordDict){
                if (i - word.length() >= 0 && s.substring(i - word.length()).indexOf(word) == 0 && flag[i - word.length()]){
                    flag[i] = true;
                    break;
                }
            }
        }
        
        return flag[s.length()];
    }
}
举报

相关推荐

0 条评论