# 139. Word-Break

difficulty: Medium

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:**

<pre><code><strong>Input: s = "leetcode", wordDict = ["leet", "code"]
</strong><strong>Output: true
</strong><strong>Explanation: Return true because "leetcode" can be segmented as "leet code".
</strong></code></pre>

**Example 2:**

<pre><code><strong>Input: s = "applepenapple", wordDict = ["apple", "pen"]
</strong><strong>Output: true
</strong><strong>Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
</strong>             Note that you are allowed to reuse a dictionary word.
</code></pre>

**Example 3:**

<pre><code><strong>Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
</strong><strong>Output: false
</strong></code></pre>

## Method One

```Java
class Solution {
    private Set<String> set;
    private boolean[] marked;
    public boolean wordBreak(String s, List<String> wordDict) {
        this.set = new HashSet<>(wordDict);
        marked = new boolean[s.length() + 1];
        Queue<Integer> bfs = new LinkedList<>();
        bfs.offer(0);
        while( !bfs.isEmpty() ) {
            int size = bfs.size();
            while ( size > 0 ) {
                size -= 1;
                int cur = bfs.poll();
                for(int i = cur + 1; i <= s.length(); i++ ) {
                    if( marked[i] ) {
                        continue;
                    }
                    if(set.contains( s.substring(cur, i) ) ) {
                        if( i == s.length() ) {
                            return true;
                        }
                        bfs.offer(i);
                        marked[i] = true;
                    }
                }
            }
        }
        return false;
    }
    
}
​
```

## Method Best: Using DP

这个题其实是个藏的比较深的动态规划的题。只是包装上了 String 就让人容易想歪。 上面的BFS的思路其实差不多，所以时间复杂度都是一样的。 仔细想一下这个题其实和 coin change 之类的一样啊。随便说一句点一下： 如果 s 的一个substring, s.substring(0, i) match上了，那么我们就不考虑之前的是否match了。 dp\[i] 标志的就是这个 substring 是否是match的。

```java
class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        boolean[] dp = new boolean[s.length() + 1];
        dp[0] = true;
        for (int i = 0; i <= s.length(); i++) {
            if (!dp[i]) continue;
            String curS = s.substring(i, s.length());
            for (String word : wordDict) {
                if (!curS.startsWith(word)) continue;
                dp[i + word.length()] = true;
            }
        }
        return dp[s.length()];
    }
}
```
