Given a list of words (without duplicates), 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:

  1. The number of elements of the given array will not exceed 10,000
  2. The length sum of elements in the given array will not exceed 600,000.
  3. All the input string will only include lower case letters.
  4. The returned elements order does not matter.

这道题给了一个由单词组成的数组,某些单词是可能由其他的单词组成的,让我们找出所有这样的单词。这道题跟之前那道Word Break十分类似,我们可以对每一个单词都调用之前那题的方法,我们首先把所有单词都放到一个unordered_set中,这样可以快速找到某个单词是否在数组中存在。对于当前要判断的单词,我们先将其从set中删去,然后调用之前的Word Break的解法,具体讲解可以参见之前的帖子。如果是可以拆分,那么我们就存入结果res中,参见代码如下:

解法一:

class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
if (words.size() <= ) return {};
vector<string> res;
unordered_set<string> dict(words.begin(), words.end());
for (string word : words) {
dict.erase(word);
int len = word.size();
if (len == ) continue;
vector<bool> v(len + , false);
v[] = true;
for (int i = ; i < len + ; ++i) {
for (int j = ; j < i; ++j) {
if (v[j] && dict.count(word.substr(j, i - j))) {
v[i] = true;
break;
}
}
}
if (v.back()) res.push_back(word);
dict.insert(word);
}
return res;
}
};

下面这种方法跟上面的方法很类似,不同的是判断每个单词的时候不用将其移除set,而是在判断的过程中加了判断,使其不会判断单词本身是否在集合set中存在,而且由于对单词中子字符串的遍历顺序不同,加了一些优化在里面,使得其运算速度更快一些,参见代码如下:

解法二:

class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
vector<string> res;
unordered_set<string> dict(words.begin(), words.end());
for (string word : words) {
int n = word.size();
if (n == ) continue;
vector<bool> dp(n + , false);
dp[] = true;
for (int i = ; i < n; ++i) {
if (!dp[i]) continue;
for (int j = i + ; j <= n; ++j) {
if (j - i < n && dict.count(word.substr(i, j - i))) {
dp[j] = true;
}
}
if (dp[n]) {res.push_back(word); break;}
}
}
return res;
}
};

下面这种方法是递归的写法,其中递归函数中的cnt表示有其他单词组成的个数,至少得由其他两个单词组成才符合题意,参见代码如下:

解法三:

class Solution {
public:
vector<string> findAllConcatenatedWordsInADict(vector<string>& words) {
vector<string> res;
unordered_set<string> dict(words.begin(), words.end());
for (string word : words) {
if (word.empty()) continue;
if (helper(word, dict, , )) {
res.push_back(word);
}
}
return res;
}
bool helper(string& word, unordered_set<string>& dict, int pos, int cnt) {
if (pos >= word.size() && cnt >= ) return true;
for (int i = ; i <= (int)word.size() - pos; ++i) {
string t = word.substr(pos, i);
if (dict.count(t) && helper(word, dict, pos + i, cnt + )) {
return true;
}
}
return false;
}
};

类似题目:

Word Break

参考资料:

https://discuss.leetcode.com/topic/72393/c-772-ms-dp-solution

https://discuss.leetcode.com/topic/72433/c-600ms-20-lines-of-code-dfs-solution-is-there-any-way-to-optimize

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] Concatenated Words 连接的单词的更多相关文章

  1. 472 Concatenated Words 连接的单词

    详见:https://leetcode.com/problems/concatenated-words/description/ C++: class Solution { public: vecto ...

  2. [LeetCode] Valid Word Square 验证单词平方

    Given a sequence of words, check whether it forms a valid word square. A sequence of words forms a v ...

  3. [LeetCode] Valid Word Abbreviation 验证单词缩写

    Given a non-empty string s and an abbreviation abbr, return whether the string matches with the give ...

  4. [LeetCode] Shortest Word Distance 最短单词距离

    Given a list of words and two words word1 and word2, return the shortest distance between these two ...

  5. [LeetCode] Short Encoding of Words 单词集的短编码

    Given a list of words, we may encode it by writing a reference string S and a list of indexes A. For ...

  6. [LeetCode] Expressive Words 富于表现力的单词

    Sometimes people repeat letters to represent extra feeling, such as "hello" -> "he ...

  7. LeetCode 79 Word Search(单词查找)

    题目链接:https://leetcode.com/problems/word-search/#/description 给出一个二维字符表,并给出一个String类型的单词,查找该单词是否出现在该二 ...

  8. LeetCode 290 Word Pattern(单词模式)(istringstream、vector、map)(*)

    翻译 给定一个模式,和一个字符串str.返回str是否符合同样的模式. 这里的符合意味着全然的匹配,所以这是一个一对多的映射,在pattern中是一个字母.在str中是一个为空的单词. 比如: pat ...

  9. LeetCode 1255 得分最高的单词集合 Maximum Score Words Formed by Letters

    地址 https://leetcode-cn.com/problems/maximum-score-words-formed-by-letters/ 题目描述你将会得到一份单词表 words,一个字母 ...

随机推荐

  1. 【Android】开发中个人遇到和使用过的值得分享的资源合集

    Android-Classical-OpenSource Android开发中 个人遇到和使用过的值得分享的资源合集 Trinea的OpenProject 强烈推荐的Android 开源项目分类汇总, ...

  2. SignalR系列续集[系列6:使用自己的连接ID]

    目录 SignalR系列目录 前言 老规矩,前言~,在此先道个歉,之前的1-5对很多细节问题都讲的不是很详细,也有很多人在QQ或者博客问我一些问题 所以,特开了这个续集.. - -, 讲一些大家在开发 ...

  3. C# http

    minihttpd minihttpd:HTTPWeb服务器库 https://www.codeproject.com/articles/11342/minihttpd-an-http-web-ser ...

  4. Redis命令拾遗二(散列类型)

    本文版权归博客园和作者吴双共同所有,欢迎转载,转载和爬虫请注明原文地址 :博客园蜗牛NoSql系列地址  http://www.cnblogs.com/tdws/tag/NoSql/ Redis命令拾 ...

  5. asp.net创建事务的方法

    1.建立List用于存放多条语句 /// <summary> /// 保存表单 /// </summary> /// <param name="context& ...

  6. IO模型

    前言 说到IO模型,都会牵扯到同步.异步.阻塞.非阻塞这几个词.从词的表面上看,很多人都觉得很容易理解.但是细细一想,却总会发现有点摸不着头脑.自己也曾被这几个词弄的迷迷糊糊的,每次看相关资料弄明白了 ...

  7. 解决ngnix服务器上的Discuz!x2.5 Upload Error:413错误

    1.修改php.ini sudo nano /etc/php5/fpm/php.ini #打开php.ini找到并修改以下的参数,目的是修改上传限制 max_execution_time = 900 ...

  8. 【前端优化之拆分CSS】前端三剑客的分分合合

    几年前,我们这样写前端代码: <div id="el" style="......" onclick="......">测试&l ...

  9. 集成shareSDK错误总结(新浪微博)

    错误1. . 以上错误是由于没有添加-ObjC的原因,在targets->Build Setting ->Other Linker Flags中添加-ObjC 添加方法如下 错误2 授权回 ...

  10. 靠谱的datatable转json方法

    今天有之前同事问我要datatable转json的方法,以前自己也弄过,但感觉网上有很多不靠谱的方法.所以自己在博客里记录一个,当然也是网上找的,但是这个靠谱一点,起码可以用不会报错,所以叫他靠谱的d ...