[LeetCode] 139. 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. You may assume the dictionary does not contain duplicate words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

Thought process:
  1. Sub-problem: determine if a substring of s can be segmented into a sequence of one or more dictionary words.
  2. Function: f[i] = if there exists (f[j] && s[j, i] is a dictionary word).
  3. Initialization: f[0] = true. Add a dummy character at the start of the string.
  4. Answer: f[s.length].

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        int length = s.length();
        
        boolean[] f = new boolean[length + 1];
        f[0] = true;
        
        for (int i = 1; i <= length; i++) {
            for (int j = 0; j < i; j++) {
                if (f[j] && wordDict.contains(s.substring(j, i))) {
                    f[i] = true;
                }
            }
        }
        
        return f[length];
    }
}

Time complexity: 
Say m = size of wordDict and n = length of s, the overall time complexity is O(mn^2).

Comments

  1. I found that solution is very popular and helpful : https://www.youtube.com/watch?v=_JYE_M3uD-Y

    ReplyDelete

Post a Comment

Popular posts from this blog

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary

[LeetCode] 631. Design Excel Sum Formula