博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】472. Concatenated Words
阅读量:7154 次
发布时间:2019-06-29

本文共 2504 字,大约阅读时间需要 8 分钟。

题目如下:

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 = 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.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.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] = 1                    break                else:                    queue += t.divide(item,False)        return res

 

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

你可能感兴趣的文章
高可用集群原理
查看>>
网络安全系列之三十三 关闭端口
查看>>
学习C#感受
查看>>
php线程实现
查看>>
linux查看命令来自哪个安装包
查看>>
堡垒机-麒麟开源堡垒机代码分析-应用发布帐号同步部分
查看>>
Ceph集群搭建
查看>>
Linux环境下使用rpm包方式安装MySQL的方法
查看>>
HTTP协议
查看>>
Java电商项目面试题(六)
查看>>
全网备份
查看>>
Java 重大升级马上来了:JDK 11 新特性了解一下
查看>>
字符串转换成NSDate类型的 为nil解决方法
查看>>
Ubuntu git 与 gitlab 关联
查看>>
C++ 上溢和下溢(overflow underflow)
查看>>
Maven_运行时环境
查看>>
动态规划——Best Time to Buy and Sell Stock III
查看>>
grid布局
查看>>
常用的mysql操作
查看>>
转: spring静态注入
查看>>