给你一个 不含重复 单词的字符串数组 words ,请你找出并返回 words 中的所有 连接词 。连接词 定义为:一个完全由给定数组中的至少两个较短单词组成的字符串。

这个博客介绍了一种解决方法,通过构建Trie数据结构查找给定字典中所有的连续组合单词。首先对输入单词进行排序,然后遍历每个单词,如果在Trie中搜索到该单词,则将其添加到结果列表中。同时,将未完成的单词插入Trie以供后续搜索。这种方法有效地找到了所有可能的组合单词。
class Solution(object):
    def findAllConcatenatedWordsInADict(self, words):
        """
        :type words: List[str]
        :rtype: List[str]
        """
        t = Trie()
        ans = []
        m = sorted(words,key = lambda i :len(i),reverse = False)
        # print(m)
        for word in m:
            if word == "":
                continue
            if t.search(word):
                ans.append(word)
            else:
                t.insert(word)
        # print(t.child)
        return ans
class Trie(object):

    def __init__(self):
        self.child = {}


    def insert(self, word):
        """
        :type word: str
        :rtype: None
        """
        nowsdata = self.child
        for s in word:
            if s not in nowsdata.keys():
                nowsdata[s] = {}
            nowsdata = nowsdata[s]
        nowsdata['#'] = '#'


    def search(self, word):
        """
        :type word: str
        :rtype: bool
        """
        nowsdata = self.child
        for i in range(len(word)):
            if '#' in nowsdata:
                if self.search(word[i:]):  # 如果if不成立则接着执行for循环
                    return True
            if word[i] not in nowsdata.keys():
                return False
            nowsdata = nowsdata[word[i]]
        return '#' in nowsdata.keys()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值