题目如下:

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.

解题思路:我的方法是Input按单词的长度升序排序后存入字典树中,因为Input中单词不重复,所有较长的单词肯定是由比其短的单词拼接而成的。每个单词在存入字典树的时候,同时做前缀匹配,并保存匹配的结果,接下来再对这些结果递归做前缀匹配,直到无法匹配或者完全匹配为止。如果有其中任意一个结果满足完全匹配,则表示这个单词可以由其他的单词拼接而成。

代码如下:

class TreeNode(object):
def __init__(self, x):
self.val = x
self.childDic = {}
self.hasWord = False class Trie(object):
dic = {}
def __init__(self):
"""
Initialize your data structure here.
"""
self.root = TreeNode(None)
self.dic = {} def divide(self, word,flag):
substr = []
current = self.root
path = ''
for i in word:
path += i
if i not in current.childDic:
current.childDic[i] = TreeNode(i)
current = current.childDic[i]
if current.hasWord:
substr.append(word[len(path):])
self.dic[path] = 1
if flag:
self.dic[word] = 1
current.hasWord = True
return substr
def isExist(self,w):
return w in self.dic class Solution(object):
def findAllConcatenatedWordsInADict(self, words):
"""
:type words: List[str]
:rtype: List[str]
"""
words.sort(cmp=lambda x1,x2:len(x1) - len(x2))
t = Trie()
res = []
for w in words:
queue = t.divide(w,True)
while len(queue) > 0:
item = queue.pop(0)
if t.isExist(item):
res.append(w)
#t.dic[w] = 1
break
else:
queue += t.divide(item,False)
return res

【leetcode】472. Concatenated Words的更多相关文章

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

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

  2. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  3. 【Leetcode】Pascal's Triangle II

    Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3 ...

  4. 53. Maximum Subarray【leetcode】

    53. Maximum Subarray[leetcode] Find the contiguous subarray within an array (containing at least one ...

  5. 27. Remove Element【leetcode】

    27. Remove Element[leetcode] Given an array and a value, remove all instances of that value in place ...

  6. 【刷题】【LeetCode】007-整数反转-easy

    [刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接-空 007-整数反转 方法: 弹出和推入数字 & 溢出前进行检查 思路: 我们可以一次构建反转整数的一位 ...

  7. 【刷题】【LeetCode】000-十大经典排序算法

    [刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接 000-十大经典排序算法

  8. 【leetcode】893. Groups of Special-Equivalent Strings

    Algorithm [leetcode]893. Groups of Special-Equivalent Strings https://leetcode.com/problems/groups-o ...

  9. 【leetcode】657. Robot Return to Origin

    Algorithm [leetcode]657. Robot Return to Origin https://leetcode.com/problems/robot-return-to-origin ...

随机推荐

  1. (转)Centos7 yum 源安装nginx

    转:https://www.cnblogs.com/fuhai0815/p/8522868.html 一.建立nginx源 vim /etc/yum.repos.d/nginx.repo [nginx ...

  2. 心形陀螺案例css3

    <!DOCTYPE html><html lang="zh-cn"><head> <meta charset="UTF-8&qu ...

  3. RequestBody 请求格式

    @RequestMapping("/CreateComment")@ResponseBodypublic String createQuestionComments(@Reques ...

  4. MyEclipse上有main函数类运行报错:Editor does not contain a

    MyEclipse下有main函数类运行报错:Editor does not contain a main type?出现这种问题的原因是,该java文件   MyEclipse下有main函数类运行 ...

  5. Python模块学习之xlrd、xlutils、openpyxl 读写/追加Excel文件

    Python操作Excel的四个工具包 xlrd: 对Excel进行读相关操作,注意只能操作 .xls xlwt: 对Excel进行写相关操作,注意只能操作 .xls,且只能创建一个全新的Excel然 ...

  6. tomcat启动控制台报Exception in thread ''main".......“Could not find the main class:.....Bootstrap”问题

    startup.bat文件打开最后end下一行加pause调试,重新启动tomcat,发现配置没问题,但是依然报错,发现是jdk版本问题,jdk1.6无法与tomcat8适配,重新装个1.7版本的jd ...

  7. WPF国际化方式1之资源文件

    先看效果吧,个人觉得由于MVVM模式的UI响应属性变化的特殊机制,资源文件和内存数据都是国际化不错的选择. 1.首先准备两个资源文件用来做中文和英文的转换使用,将程序中需要转换语言都弄成两个版本,分别 ...

  8. 关于Visual Studio中书签Bookmark的一些问题

    VS自带一个书签功能,但是有个大问题,没有导出功能,因为这个书签是保存在工程.suo文件中,所以在移动,分享,甚至其他情况下很不方便,甚至丢失. 在你分析一个较大的开源,做了30-50个关键代码书签, ...

  9. 远程操作 SQl server2008新建角色和数据库

    远程操作 SQl server2008 1.windows身份登录,安全性-->登录名(右键)-->新建登录名:yc ,密码111111-->点选sql server身份验证--&g ...

  10. 《STL源码剖析》——第一、二、三章

     第一章:概论: 换句话说,STL所实现的,是依据泛型思维架设起来的一个概念结构.这个以抽象概念(abstract concepts)为主体而非以实际类(classes)为主体的结构,形成了一个严谨的 ...