1. 程式人生 > >LeetCode刷題MEDIM篇Word Break

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()];
    }
}