题目如下:

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 = xself.childDic = {}self.hasWord = Falseclass 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.rootpath = ''for i in word:path += iif 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] = 1if flag:self.dic[word] = 1current.hasWord = Truereturn substrdef isExist(self,w):return w in self.dicclass 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] = 1breakelse:queue += t.divide(item,False)return res

转载于:https://www.cnblogs.com/seyjs/p/10508910.html

【leetcode】472. Concatenated Words相关推荐

  1. 【Leetcode】100. 相同的树

    题目 给定两个二叉树,编写一个函数来检验它们是否相同. 如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的. 示例 1: 输入: 1 1/ \ / \2 3 2 3[1,2,3], [1 ...

  2. 【leetcode】85. Maximal Rectangle 0/1矩阵的最大全1子矩阵

    1. 题目 Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1 ...

  3. 【leetcode】486. Predict the Winner

    题目如下: Given an array of scores that are non-negative integers. Player 1 picks one of the numbers fro ...

  4. 【leetcode】132. Palindrome Partitioning II

    题目如下: 解题思路:本题是[leetcode]131. Palindrome Partitioning的升级版,要求的是求出最小cuts,如果用[leetcode]131. Palindrome P ...

  5. 【leetcode】86. Partition List

    题目如下: Given a linked list and a value x, partition it such that all nodes less than x come before no ...

  6. 【Leetcode】103. 二叉树的锯齿形层次遍历

    题目 给定一个二叉树,返回其节点值的锯齿形层次遍历.(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行). 例如: 给定二叉树 [3,9,20,null,null,15,7], 3 ...

  7. 【Leetcode】79.单词搜索

    题目 给定一个二维网格和一个单词,找出该单词是否存在于网格中. 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中"相邻"单元格是那些水平相邻或垂直相邻的单元格.同一个单元格 ...

  8. 【LeetCode】字符串 string(共112题)

    [3]Longest Substring Without Repeating Characters (2019年1月22日,复习) [5]Longest Palindromic Substring ( ...

  9. 【leetcode】 算法题1 两数之和

    [leetcode] 算法题1 两数之和 问题   给定一个整数数组和一个目标值,找出数组中和为目标值的两个数. 你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用. 示例: 给定 nums ...

最新文章

  1. 【组队学习】【30期】时间序列分析
  2. 面试官:你能说说事务的几个特性是啥?有哪几种隔离级别?
  3. 双机热备软件,Legato AAM,双机容错,集群软件,磁盘阵列
  4. C#委托的定义 以及使用方式详解,更简单的理解委托。
  5. 【转】概要设计说明书
  6. 【全】.net core平台单元/集成测试结果、覆盖率、圈复杂度到可视化HTML报告之路...
  7. java.nio.file 找不到_java - 断言该错误:无法访问路径(找不到java.nio.file.Path) - 堆栈内存溢出...
  8. Mysql报错130_Mysql报错Forcing close of thread 139 user: 'root'
  9. angularjs--resource
  10. android权限列表
  11. Unity3D基础8:C#脚本
  12. 《网络攻防第六周作业》
  13. ★一张图弄明白从零维到十维
  14. 构建WindowsPhone生态:梁念坚博士答记者问windowsphone
  15. php-win.exe 是什么,windows桌面指的是什么
  16. 结巴分词有前空格_jieba英文空格分词问题
  17. OracleDataAdapter.Fill()处于无限等待中 【已解决】
  18. 人脸识别(Facenet)
  19. PS 图像调整算法——饱和度调整
  20. Pandas是什么?Pandas库下载和安装!

热门文章

  1. 基于HBASE的并行计算架构之rowkey设计篇
  2. 韦东山驱动视频笔记——3.字符设备驱动程序之poll机制
  3. mysql increment by 2_关于mysql auto-increment
  4. 公众号点击图片变成另一张_微信公众号点击出现图片是怎么实现的?
  5. 使用java理解程序逻辑 第十二章_Java弱引用的理解与使用
  6. JavaWeb(十一)——登录注册小案例
  7. java pdf 书签_Java PDF书签——添加、编辑、删除、读取书签
  8. 毕业论文 | 信号的抽取与插值技术研究(源代码)
  9. Qt学习(六):UDP通信
  10. php 自定义条件,php – 使用两个条件自定义排序数组数组