720. 词典中最长的单词

在这里插入图片描述

记录每一个单词的前缀,看前缀是否在集合中,如果前缀都在集合中,则添加单词,最后求最长的最小单词。

class Solution(object):
    def longestWord(self, words):
        ans = []
        wordset = set(words)
        for word in words:
            flag = 1
            for i in range(1,len(word)):
                if word[:i] not in wordset:
                    flag = 0
            if flag == 1:
                ans.append(word)
        if ans == []:
            return ""
        ans.sort(key=lambda x:[len(x), x],reverse=True)
        l = len(ans[0])
        res = ans[0]
        for i in range(len(ans)):
            if len(ans[i]) == l:
                if res > ans[i]:
                    res = ans[i]
            else:
                break
        return res

前缀树

在这里插入图片描述
在这里插入图片描述

from collections import defaultdict


class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.word = False


class Trie:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TrieNode()


    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        cur = self.root
        for w in word:
            cur = cur.children[w]
        cur.word = True


    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        cur = self.root
        for w in word:
            if w not in cur.children:
                return False
            cur = cur.children[w]
        if cur.word:
            return True
        return False


    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        cur = self.root
        for p in prefix:
            if p not in cur.children:
                return False
            cur = cur.children[p]
        return True

720用前缀树解法,注意这里的需要判断前缀是否存在,搜索的时候每个词已经存在,所以直接判断当前词是否是结尾的词。

from collections import defaultdict


class TrieNode:
    def __init__(self):
        self.children = defaultdict(TrieNode)
        self.word = False


class Trie:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TrieNode()


    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        cur = self.root
        for w in word:
            cur = cur.children[w]
        cur.word = True


    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        cur = self.root
        for w in word:
            cur = cur.children[w]
            if not cur.word :
                return False
        if cur.word:
            return True
        return False


class Solution:
    def longestWord(self, words: List[str]) -> str:
        res=''
        trie=Trie()
        for word in words:
            trie.insert(word)
        for word in words:
            if trie.search(word):
                if len(word) > len(res):
                    res=word
                elif len(word)==len(res) and word < res:
                    res=word
        return res

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值