LeetCode刷题MEDIM篇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

十分钟尝试

尝试用dp思路去解决,但是不知道如何写转化方程。

dp[i]如果满足条件,需要dp[i-1]满足条件,如何定义呢?看下面的关键点,如果f[j]可以由字典单词组成,并且s[j,i](左闭右开)在字典中国,那么f[i]就是可以组成,他的值就是true。

f[j] is to check if s[0:j] (0 inclusive, j exclusive) can be composed of words in wordDict, if both f[j] is true and s[j:i] (j inclusive, i exclusive) is in wordDict, then we can say f[i] is true. (Note that f's length is 1 more than s's length, which can cause some confusion

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

猜你喜欢

转载自blog.csdn.net/hanruikai/article/details/85986815