Java实现 LeetCode 140 单词拆分II

class Solution {
     public List<String> wordBreak(String s, List<String> wordDict) {
 
        List<String> res = new ArrayList<>();
        int max = 0, min = Integer.MAX_VALUE;
        Set<String> set = new HashSet<>();
        for (String word : wordDict) {
            set.add(word);
            max = Integer.max(max, word.length());
            min = Integer.min(min, word.length());
        }
 
        boolean f[] = new boolean[s.length() + 1];
        f[0] = true;
        for (int i = 1; i < s.length() + 1; i++) {
            for (int j = Math.max(i - max, 0); j <= i - min; j++) {
                if (f[j] && set.contains(s.substring(j, i))) {
                    f[i] = true;
                    break;
                }
            }
        }
        if (f[s.length()]) {
            dfs(s, res, new StringBuilder(), set, 0, max, min);
        }
        return res;
    }
 
    private void dfs(String s, List<String> res, StringBuilder sb, Set<String> set, int index, int max, int min) {
        if (index == s.length()) {
            sb.deleteCharAt(sb.length() - 1);
            res.add(sb.toString());
            return;
        }
        String str;
        int size;
        for (int i = index + min; i <= s.length() && i <= index + max; i++) {
            if (set.contains(str = s.substring(index, i))) {
                size = sb.length();
                sb.append(str).append(' ');
                dfs(s, res, sb, set, i, max, min);
                sb.delete(size, sb.length());
            }
        }
    }
}
上一篇:[转载] 140种Python标准库、第三方库和外部工具


下一篇:【Java力扣算法】LeetCode 140 单词拆分II(有待改进)