Word Break

LeetCode Q 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.

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

Solution : DP bottom-up

  1. State: boolean dp[i] represents if s.substring(0, i+1) is valid.

  2. state transfer fuction:
    For String s.substring(0, i+1), we divide it into two parts, one is s.substring(0, j) and another is s.substring(j, i+1) if they are all valid then s.substring(0, i+1) is valid.
    Therefore,
    dp[i] = dp[j] && wordDict.contains(s.substring(j, i+1));

Caution: when we find one valid partition of s.substring(0, i+1), we need to break the for loop.

  1. boundary cases: dp[0] = true.

Code:

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

   Reprint policy


《Word Break》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC