zoukankan      html  css  js  c++  java
  • 【leetcode】745. Prefix and Suffix Search

    题目如下:

    Given many wordswords[i] has weight i.

    Design a class WordFilter that supports one function, WordFilter.f(String prefix, String suffix). It will return the word with given prefix and suffix with maximum weight. If no word exists, return -1.

    Examples:

    Input:
    WordFilter(["apple"])
    WordFilter.f("a", "e") // returns 0
    WordFilter.f("b", "") // returns -1

    Note:

    1. words has length in range [1, 15000].
    2. For each test case, up to words.length queries WordFilter.f may be made.
    3. words[i] has length in range [1, 10].
    4. prefix, suffix have lengths in range [0, 10].
    5. words[i] and prefix, suffix queries consist of lowercase letters only.

    解题思路:以输入apple为例,前缀和后缀分别有6个,分别为"","a","ap","app","appl","apple",两者组合起来就是36个。words中最长的word的长度是10,那么组合就是11*11 = 121个,words的最大长度是15000,总的组合个数1815000,似乎在可以接受的范围之内。所以,只要预先把所有单词的所有前缀后缀的组合预先计算出来,那么查找的时间复杂度就是O(1)了。

    代码如下:

    class WordFilter(object):
    
        def __init__(self, words):
            """
            :type words: List[str]
            """
            self.dic = {}
            for i in range(len(words)-1,-1,-1):
                word = words[i]
                foward = ''
                reverse = word
                while len(reverse) >= 0:
                    if (foward,reverse) not in self.dic:
                        self.dic[(foward,reverse)] = i
                    for j in range(len(word)):
                        foward += word[j]
                        if (foward,reverse) not in self.dic:
                            self.dic[(foward,reverse)] = i
                    if len(reverse) > 0:reverse = reverse[1:]
                    else:break
                    foward = ''
    
        def f(self, prefix, suffix):
            """
            :type prefix: str
            :type suffix: str
            :rtype: int
            """
            if (prefix,suffix) in self.dic:
                return self.dic[(prefix,suffix)]
            return -1
  • 相关阅读:
    VS2017使用inet_ntoa()产生错误的解决方法
    ET框架:如何运行ET-Demo
    ProtoBuf入门
    AssetBundle入门
    UML图写法
    Visual Studio小技巧-引用项目外部的类
    UnityECS(一)UnityECS学习资料
    关于如何利用MySQL Workbench导入Excel表格
    SublimeText3插件安装(未完更新)
    Unity中Animator的2DSprite动画控制与使用
  • 原文地址:https://www.cnblogs.com/seyjs/p/11947362.html
Copyright © 2011-2022 走看看