日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【leetcode】472. Concatenated Words

發布時間:2025/3/8 编程问答 43 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【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 = 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的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。