LeetCode 139. Word Break

Description

https://leetcode.com/problems/word-break/description/

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:

Example 2:

Example 3:

Explanation

We need to determine if s can be segmented into a space-separated sequence of one or more dictionary words.

We can introduce a state variable isWordBreak[i] to indicate whether the first iith characters of the input string is able to break into words that all in the dictionary.

Set isWordBreak[0] to true, indicating that empty string ”” is also in the wordDict.

  • isWordBreak[j] is used to indicate whether the first j characters of the input string is able to break into words that all in the dictionary
  • Only when isWordBreak[j] = true(first j characters of the input string is word breakable) and s.substring(j, i) is also a word in the wordDict, first i characters of s can be word breakable.

Video Tutorial

Java Solution

2 Thoughts to “LeetCode 139. Word Break”

  1. “isWordBreak[4]==TRUE && s.substring(4,10) in WordDict”

    In this statement, don’t we need to distinguish whether s.substring(5,10) is in WordDict or not?
    So in the code,
    if (wordDict.contains(s.substring(j+1, i))) {
    isWordBreak[i] = true;
    break;
    }

Leave a Reply

Your email address will not be published. Required fields are marked *