139 Word Break

1. Question

Given a non-empty strings and a dictionary wordDict containing a list of non-empty words, determine if scan 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".

2. Implementation

(1) DFS + Memoinzation

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Map<Integer, Boolean> map = new HashMap<>();
        Set<String> dict = new HashSet<>(wordDict);

        return isBreakable(0, s, dict, map);
    }

    public boolean isBreakable(int start, String s, Set<String> dict, Map<Integer, Boolean> map) {
        if (start == s.length()) {
            return true;
        }

        if (map.containsKey(start)) {
            return map.get(start);
        }

        boolean breakable = false;

        for (int end = start + 1; end <= s.length(); end++) {
            if (dict.contains(s.substring(start, end)) && isBreakable(end, s, dict, map)) {
                breakable = true;
            }
        }

        map.put(start, breakable);
        return breakable;
    }
}

(2) DP

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> dict = new HashSet<>(wordDict);
        int n = s.length();
        boolean[] dp = new boolean[n + 1];
        dp[0] = true;

        for (int i = 1; i <= n; i++) {
            for (int j = 0; j < i; j++) {
                if (dp[j] && dict.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[n];
    }
}

3. Time & Space Complexity

DFS + Memoinzation: 时间复杂度O(n^2), 空间复杂度O(n)

DP: 时间复杂度O(n^2), 空间复杂度O(n)

Last updated