【leetcode】472. Concatenated Words
题目如下:
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:
- 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.
解题思路:我的方法是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的更多相关文章
- 【LeetCode】472. Concatenated Words 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址:https://leetc ...
- 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java
[LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...
- 【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 ...
- 53. Maximum Subarray【leetcode】
53. Maximum Subarray[leetcode] Find the contiguous subarray within an array (containing at least one ...
- 27. Remove Element【leetcode】
27. Remove Element[leetcode] Given an array and a value, remove all instances of that value in place ...
- 【刷题】【LeetCode】007-整数反转-easy
[刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接-空 007-整数反转 方法: 弹出和推入数字 & 溢出前进行检查 思路: 我们可以一次构建反转整数的一位 ...
- 【刷题】【LeetCode】000-十大经典排序算法
[刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接 000-十大经典排序算法
- 【leetcode】893. Groups of Special-Equivalent Strings
Algorithm [leetcode]893. Groups of Special-Equivalent Strings https://leetcode.com/problems/groups-o ...
- 【leetcode】657. Robot Return to Origin
Algorithm [leetcode]657. Robot Return to Origin https://leetcode.com/problems/robot-return-to-origin ...
随机推荐
- elasticsearch 集群搭建及启动常见错误
1.系统环境 三台服务器(最好是单数台,跟master选举方式有关),确保机器互相ping的通,且都需要装了jdk 8环境,机器IP和 elasticsearch 的节点名称如下: cluster n ...
- leetcode 189. 旋转数组(python)
给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数. 示例 1: 输入: [1,2,3,4,5,6,7] 和 k = 3输出: [5,6,7,1,2,3,4]解释:向右旋转 1 步: ...
- Spring中两种引入配置文件方式
用过Spring的人都知道,我们一般把数据库的配置.日志的配置或者其他的通用配置放在单独的配置文件中,在和Spring整合时,一般通过以下两种方法引入: <context:property-pl ...
- PHP中的九大缓存技术
1.全页面静态化缓存也就是将页面全部生成html静态页面,用户访问时直接访问的静态页面,而不会去走php服务器解析的流程.此种方式,在CMS系统中比较常见,比如dedecms: 一种比较常用的实现方式 ...
- ToString()的简单介绍
1.在某一个类中重写该类的toString()方法,是为了方便打印该类实例中的内容.
- webpack2.0 基本使用
webpack是一款前端模块打包工具, 它的出现是由于现代web开发越来越复杂,如果还是像原来那样把所有的js代码都写到一个文件中,维护非常困难.而解决复杂化的方法通常是分而治之,就是把复杂化的东西进 ...
- [fw]linux测试工程介绍(Linux Test Project)
http://ltp.sourceforge.net/ Linux Test Project, 后台很硬,由SGI™ 发起, IBM维护,所以质量有保障. 里面介绍了很多工具,对于一般的基准测试应该是 ...
- thinkphp开发微信小程序后台流程
thinkphp开发微信小程序后台流程,简单分享一下微信开发流程 1,注册微信小程序账号 2,注册好后,登陆微信小程序,下载微信小程序开发工具 3,用thinkphp开发企业后台,前台数据用json返 ...
- G a+b+c+d=?
G a+b+c+d=? 链接:https://ac.nowcoder.com/acm/contest/338/G来源:牛客网 题目描述 This is a very simple problem! Y ...
- Visual Studio 插件ReSharper:代码生成工具
下载地址:http://www.jetbrains.com/resharper/download/download-thanks.html?code=RSU&platform=windows ...