• 边工作边刷题:70天一遍leetcode: day 88


    Unique Word Abbreviation
    要点:

    • 简单题,主要是理解题意。no other words have the same abbreviation as the given word意思就是如果没有同样的abbrev或者有但是只由dict中相同的word产生。
    • 可以用True/False表示unique,同时用set来保存哪个word产生的abbrev

    https://repl.it/CnNt

    # An abbreviation of a word follows the form <first letter><number><last letter>. Below are some examples of word abbreviations:
    
    # a) it                      --> it    (no abbreviation)
    
    #      1
    # b) d|o|g                   --> d1g
    
    #               1    1  1
    #      1---5----0----5--8
    # c) i|nternationalizatio|n  --> i18n
    
    #               1
    #      1---5----0
    # d) l|ocalizatio|n          --> l10n
    # Assume you have a dictionary and given a word, find whether its abbreviation is unique in the dictionary. A word's abbreviation is unique if no other word from the dictionary has the same abbreviation.
    
    # Example: 
    # Given dictionary = [ "deer", "door", "cake", "card" ]
    
    # isUnique("dear") -> false
    # isUnique("cart") -> true
    # isUnique("cane") -> false
    # isUnique("make") -> true
    
    
    class ValidWordAbbr(object):
        def __init__(self, dictionary):
            """
            initialize your data structure here.
            :type dictionary: List[str]
            """
            self.countmap = {}
            self.words = set(dictionary)
            
            for w in self.words:
                abw = self.getAbbre(w)
                self.countmap[abw]=True if abw not in self.countmap else False
    
        def isUnique(self, word):
            """
            check if a word is unique.
            :type word: str
            :rtype: bool
            """
            w = self.getAbbre(word)
            return w not in self.countmap or (self.countmap[w] and word in self.words)
            
        def getAbbre(self, word):
            n = len(word)
            if n<=2: return word
            return word[0]+str(n-2)+word[n-1]
    
    # Your ValidWordAbbr object will be instantiated and called as such:
    # vwa = ValidWordAbbr(dictionary)
    # vwa.isUnique("word")
    # vwa.isUnique("anotherWord")
    
  • 相关阅读:
    Bellman-Ford(BF)和Floyd算法
    Dijkstra实现最短路径
    【图论】连通分量个数(并查集)
    【模拟】n a^o7 !
    【图论】最小生成树
    【搜索DFS】图的深度遍历(dfs)
    【搜索BFS】poj3278--Catch That Cow(bfs)
    【图论】判断给定图是否存在合法拓扑序列
    二叉排序树
    【树】判断给定森林中有多少棵树(简单做法)
  • 原文地址:https://www.cnblogs.com/absolute/p/5815807.html
Copyright © 2020-2023  润新知