Given a list of words, please write a program that returns all concatenated words in the given list of words.

A concatenated word is defined as a string that is comprised entirely of at least two shorter words in the given array.

Example:
Input: ["cat","cats","catsdogcats","dog","dogcatsdog","hippopotamuses","rat","ratcatdogcat"] Output: ["catsdogcats","dogcatsdog","ratcatdogcat"] Explanation: "catsdogcats" can be concatenated by "cats", "dog" and "cats";
"dogcatsdog" can be concatenated by "dog", "cats" and "dog";
"ratcatdogcat" can be concatenated by "rat", "cat", "dog" and "cat".
Note:
The number of elements of the given array will not exceed 10,000
The length sum of elements in the given array will not exceed 600,000.
All the input string will only include lower case letters.
The returned elements order does not matter.

Scan through array and DP:

We iterate through each word and see if it can be formed by using other words. The subproblem is Word Break I.

But it is a little different from Word Break I, because our result only want words that are concantenated by 2 or more other words in the given array.

How to tell if a word is only by itself in the given array, or it can be concatenated by other words in the given array?

The trick is: it is obvious that a word can only be formed by words shorter than it. So we can first sort the input by length of each word, and only try to form one word by using words in front of it. We also do not add the current word to dictionary when determine if it can be concantenated.

小心一个test case:

Input:[""]
Output:[""]
Expected:[]
如果不加21行那句,就会直接return dp[0], true了
 public class Solution {
public List<String> findAllConcatenatedWordsInADict(String[] words) {
List<String> res = new ArrayList<>();
if (words==null || words.length==0) return res;
HashSet<String> dict = new HashSet<>();
Arrays.sort(words, new Comparator<String>() {
public int compare(String str1, String str2) {
return str1.length() - str2.length();
}
}); for (String word : words) {
if (canForm(word, dict))
res.add(word);
dict.add(word);
}
return res;
} public boolean canForm(String word, HashSet<String> dict) {
if (dict.isEmpty()) return false;
boolean[] dp = new boolean[word.length()+1];
dp[0] = true;
for (int i=1; i<=word.length(); i++) {
for (int j=0; j<i; j++) {
if (!dp[j]) continue;
String str = word.substring(j, i);
if (dp[j] && dict.contains(str)) {
dp[i] = true;
break;
}
}
}
return dp[word.length()];
}
}

这题还应该研究一下Trie的解法, 目前还没有想好,也没有看到不错的Trie 解法

Leetcode: Concatenated Words的更多相关文章

  1. [LeetCode] Concatenated Words 连接的单词

    Given a list of words (without duplicates), please write a program that returns all concatenated wor ...

  2. 【LeetCode】472. Concatenated Words 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址:https://leetc ...

  3. [LeetCode] Split Concatenated Strings 分割串联字符串

    Given a list of strings, you could concatenate these strings together into a loop, where for each st ...

  4. LeetCode Split Concatenated Strings

    原题链接在这里:https://leetcode.com/problems/split-concatenated-strings/description/ 题目: Given a list of st ...

  5. LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters

    原题链接在这里:https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters ...

  6. [LeetCode] 555. Split Concatenated Strings 分割串联字符串

    Given a list of strings, you could concatenate these strings together into a loop, where for each st ...

  7. 【leetcode】472. Concatenated Words

    题目如下: Given a list of words (without duplicates), please write a program that returns all concatenat ...

  8. 【leetcode】1239. Maximum Length of a Concatenated String with Unique Characters

    题目如下: Given an array of strings arr. String s is a concatenation of a sub-sequence of arr which have ...

  9. 【LeetCode】555. Split Concatenated Strings 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 遍历 日期 题目地址:https://leetcode ...

随机推荐

  1. iOS AFOAuth2Manager使用心得

    github地址:  https://github.com/AFNetworking/AFOAuth2Manager 这个库,不多说,实现OAuth 2.0授权访问. 确实可以减轻很大的负担,而且使用 ...

  2. fork()创建子进程

    fork()系统调用是Unix下以自身进程创建子进程的系统调用,一次调用,两次返回,如果返回是0,则是子进程,如果返回值>0,则是父进程(返回值是子进程的pid) 在fork()的调用处,整个父 ...

  3. 洛谷 P1026 统计单词个数 Label:dp

    题目描述 给出一个长度不超过200的由小写英文字母组成的字母串(约定;该字串以每行20个字母的方式输入,且保证每行一定为20个).要求将此字母串分成k份(1<k<=40),且每份中包含的单 ...

  4. git revert和git reset的区别

    git revert 是撤销某次操作,此次操作之前的commit都会被保留 git reset 是撤销某次提交,但是此次之后的修改都会被退回到暂存区 具体一个例子,假设有三个commit, git s ...

  5. 浏览器版本不支持页面示例 supper.html

    关键点在于<html>标签和js.<!--[if lt IE 10]>的配合 使用360浏览器兼容模式下查看:http://runjs.cn/code <!DOCTYPE ...

  6. 【整理】深入理解拉格朗日乘子法(Lagrange Multiplier) 和KKT条件

    在求解最优化问题中,拉格朗日乘子法(Lagrange Multiplier)和KKT(Karush Kuhn Tucker)条件是两种最常用的方法.在有等式约束时使用拉格朗日乘子法,在有不等约束时使用 ...

  7. C++ 画星号图形——空心矩形(核心代码记录)

    int mi=(int)a; int mj=(int)b; ;i<mi;i++) { ;j<mj;j++) { ||i==mi-) cout<<"*"; | ...

  8. linux一些基本命令

    linux查看自己外网ip:curl ifconfig.me 删除目录:rm -rf 目录名 查看版本:rpm -q 版本 修改文件的用户权限:chown kds:kds agent.crontab修 ...

  9. 【emWin】例程六:设置颜色

    实验指导书及代码包下载: 链接:http://pan.baidu.com/s/1eSidREy 密码:ru3c 实验现象:

  10. JQuery中on()函数详解

    JQuery API中定义的on方法,专业名词很多,读起来并不是那么容易,而对于开发人员知道函数怎么使用就可以了.本文将JQuery的说明翻译如下: on(events,[selector],[dat ...