【leetcode】472. Concatenated Words
生活随笔
收集整理的這篇文章主要介紹了
【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:
解題思路:我的方法是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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于中国剩余定理
- 下一篇: hyperledge环境安装