LeetCode 139: Word Break

Problem Description

Explanation

To solve this problem, we can use dynamic programming. We will create a boolean array dp of size s.length() + 1, where dp[i] will be true if the substring s[0:i] can be segmented into words from the dictionary. We iterate over the string s and at each position, we check if any prefix of the current substring is in the dictionary and if the remaining suffix is also part of the segmented words.

Algorithm:

  1. Initialize a boolean array dp of size s.length() + 1 where dp[i] indicates if the substring s[0:i] can be segmented into words from the dictionary.
  2. Set dp[0] = true since an empty string can be segmented.
  3. Iterate over the string s and at each position i, iterate from 0 to i to check if any prefix of the current substring is in the dictionary and if the remaining suffix is also part of the segmented words.
  4. Update dp[i] if the current substring can be segmented.
  5. Return dp[s.length()].

Time Complexity:

The time complexity of this solution is O(n^2) where n is the length of the input string s.

Space Complexity:

The space complexity of this solution is O(n) where n is the length of the input string s.

Solutions

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

Loading editor...