Leetcode: Concatenated Words

时间:2022-10-31 20:27:32
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. &lbrack;LeetCode&rsqb; Concatenated Words 连接的单词

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

  2. 【LeetCode】472&period; Concatenated Words 解题报告(C&plus;&plus;)

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

  3. &lbrack;LeetCode&rsqb; 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&period; Maximum Length of a Concatenated String with Unique Characters

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

  6. &lbrack;LeetCode&rsqb; 555&period; Split Concatenated Strings 分割串联字符串

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

  7. 【leetcode】472&period; Concatenated Words

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

  8. 【leetcode】1239&period; 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&period; Split Concatenated Strings 解题报告&lpar;C&plus;&plus;&rpar;

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

随机推荐

  1. UVA 11294 Wedding(2-sat)

    2-sat.不错的一道题,学到了不少. 需要注意这么几点: 1.题目中描述的是有n对夫妇,其中(n-1)对是来为余下的一对办婚礼的,所以新娘只有一位. 2.2-sat问题是根据必然性建边,比如说A与B ...

  2. Warning&colon; Function created with compilation errors!

    解决方案: sqlplus / as sysdba grant execute on UTL_I18N to scott; grant execute on DBMS_CRYPTO to scott;

  3. Howto Setup yum repositories to update or install package from ISO CDROM Image

    Step # 1: Mount an ISO file Type the following command (replace iso file name with the actual iso fi ...

  4. 常用 API

    运行 Java 程序的参数.使用 Scanner 获取键盘输入.使用 BufferedReader 获取键盘输入.System类.Runtime类.Object类.Java 7新增的 Objects ...

  5. Ionic项目中使用极光推送-android

    对于Ionic项目中使用消息推送服务,Ionic官方提供了ngCordova项目,这个里面的提供了用angularjs封装好的消息推送服务(官方文档),使用的是GitHub上的 PushPlugin ...

  6. linux和win7设置静态ip

    ubuntu 静态ip设置 检查网络ifconfig (不是ipconfig)必须有2个地址一个回送地址:127.0.0.1一个实际地址:192.168.3.58 sudo vim /etc/netw ...

  7. Linux 链接详解----动态链接库

    静态库的缺点: 库函数被包含在每一个运行的进程中,会造成主存的浪费. 目标文件的size过大 每次更新一个模块都需要重新编译,更新困难,使用不方便. 动态库: 是一个目标文件,包含代码和数据,它可以在 ...

  8. Invalid bound statement &lpar;not found&rpar;解决方法

    项目背景:SSM框架,MySQL数据库 报错情况: 错误原因:Mybatis的xml文件中,namespace路径错误!!引入的不是对应的Dao接口!!! Dao接口和对应的xml文件 必须一一对应! ...

  9. Python之字符串方法

    def capitalize(self): # 第一个字符变大写 def center(self, width, fillchar=None): # 内容居中,两端可指定内容填充 def count( ...

  10. python 内置数据类型之数字

    目录: 1.2. 数字 1.2.1. 数字类型 1.2.2. 浮点数 1.2.3. 进制记数 1.2.4. 设置小数精度 1.2.5. 分数 1.2.6. 除法 1.2 数字   1.2.1 数字类型 ...