【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 ...
随机推荐
- 为 PhpStorm 配置 Xdebug 来调试代码
当项目越来越复杂,排错就越发困难. 你以为代码是这么运行的,但就是有未想到的功能导致流程变得不可捉摸. 此时我们需要调试啊调试... PhpStorm 是一款优秀的 PHP IDE,排除其 Java ...
- 解决Win7部分便笺的元数据已被损坏的方法
Win7部分便笺的元数据已被损坏的方法 我们使用键盘上"Win+F"组合键搜索功能,直接找到"inkobj.dll"这个文件,一般会搜索出来好多,先随便选一个. ...
- DR 项目小结
前言 个人的项目总结, 非技术类博文. 需要补充的知识点 HTTP 协议与其内置方法 curl 指令和各选项的意义 Keystone 认证流程和各项目配置文件 [keystone_authtoken] ...
- get_date.sh
#!/usr/bin#####################################################################日期函数处理#获取某个月份的天数 getM ...
- 简单谈谈Netty的高性能之道
传统RPC 调用性能差的三宗罪 网络传输方式问题:传统的RPC 框架或者基于RMI 等方式的远程服务(过程)调用采用了同步阻塞IO,当客户端的并发压力或者网络时延增大之后,同步阻塞IO 会由于频繁的w ...
- HttpUrlConnection工具类
package com.ligotop.core.utils; import com.ligotop.core.exceptions.BusinessException; import java.io ...
- JsonView视图
同一个对象,在不同的场景,返回不同的属性,如getUserById返回User对象包含password值,而getAllUsers返回User集合,不包含password值(通过接口查看显示,序列化的 ...
- Python入门习题8.羊车门问题
例8. 羊车门问题描述:有3扇关闭的门,一扇后停着汽车,另外两扇门后是山羊,主持人知道每扇门后是什么.参赛者首先选择一扇门.在开启它之前,主持人会从另外两扇门中打开一扇门,露出门后的山羊.此时,允许参 ...
- go 协程(Goroutine)
Go 协程是什么? Go 协程是与其他函数或方法一起并发运行的函数或方法.Go 协程可以看作是轻量级线程.与线程相比,创建一个 Go 协程的成本很小.因此在 Go 应用中,常常会看到有数以千计的 Go ...
- ReplaceAll 特殊字符处理
用到Json与replaceAll Http拦截脚本中经常需要替换,replace虽然不需要处理特殊字符,但是不能匹配多个,ReplaceAll能够使用正则,不过需要处理的转移实在太多 比如,需要替换 ...