面试算法-128-单词拆分 II

题目

给定一个字符串 s 和一个字符串字典 wordDict ,在字符串 s 中增加空格来构建一个句子,使得句子中所有的单词都在词典中。以任意顺序 返回所有这些可能的句子。

注意:词典中的同一个单词可能在分段中被重复使用多次。

示例 1:

输入:s = “catsanddog”, wordDict = [“cat”,“cats”,“and”,“sand”,“dog”]
输出:[“cats and dog”,“cat sand dog”]

class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        LinkedList<String> path = new LinkedList<>();
        List<String> result = new ArrayList<>();
        dfs(s, wordDict, 0, path, result);
        return result;
    }

    public void dfs(String s, List<String> wordDict, Integer index, LinkedList<String> path,
            List<String> result) {
        if (index == s.length()) {
            result.add(String.join(" ", path));
            return;
        }

        if (index > s.length()) {
            return;
        }

        for (int i = 0; i < wordDict.size(); i++) {
            String item = wordDict.get(i);
            if (s.startsWith(item, index)) {
                path.add(item);
                dfs(s, wordDict, index + item.length(), path, result);
                path.removeLast();
            }
        }

    }
}

相关推荐

  1. 面试算法-128-单词 II

    2024-04-03 20:38:03       40 阅读
  2. 面试算法-99-单词

    2024-04-03 20:38:03       38 阅读
  3. 算法】【动规】单词

    2024-04-03 20:38:03       60 阅读
  4. 算法刷题day46】Leetcode:139. 单词

    2024-04-03 20:38:03       35 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-03 20:38:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-03 20:38:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-03 20:38:03       82 阅读
  4. Python语言-面向对象

    2024-04-03 20:38:03       91 阅读

热门阅读

  1. RabbitMQ

    2024-04-03 20:38:03       31 阅读
  2. Ceph常用命令总结

    2024-04-03 20:38:03       35 阅读
  3. 面试题多态结合线程

    2024-04-03 20:38:03       40 阅读
  4. MATLAB 按照索引提取点云 (56)

    2024-04-03 20:38:03       45 阅读
  5. Qt控件样式设置其一(常见方法及优缺点)

    2024-04-03 20:38:03       34 阅读
  6. Neo4j基础知识

    2024-04-03 20:38:03       39 阅读
  7. Spring中最常用的11个扩展点

    2024-04-03 20:38:03       32 阅读
  8. ctf.show_web11

    2024-04-03 20:38:03       38 阅读
  9. C++ //练习 11.11 不使用decltype重新定义bookstore。

    2024-04-03 20:38:03       37 阅读
  10. 串匹配【C++ 实现】

    2024-04-03 20:38:03       40 阅读
  11. Linux的Shell基础知识总结

    2024-04-03 20:38:03       35 阅读
  12. redis简介

    2024-04-03 20:38:03       38 阅读