[LeetCode] 288.Unique Word Abbreviation 独特的单词缩写
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
一个单词的缩写可以表示成第一个字母+中间字母个数+最后一个字母。给一个单词字典和一个单词,判断这个单词的缩写是唯一的,即字典的单词缩写中没有这个缩写或者有这个缩写但和这个单词是一样的(注意这种情况的处理)。
解法:定义一个函数用来操作缩写单词,对于字典中的所有单词进行缩写并存入另一个哈希表(key为缩写后的单词,value为set)。再对单词进行缩写,然后判断单词的缩写是否在哈希表中出现,如果没出现那肯定是唯一的。如果出现了还要看set里存的是不是只是这个单词,如果有其它单词出现就不是唯一的。
Java:
public class ValidWordAbbr { Map<String, Set<String>> map; public ValidWordAbbr(String[] dictionary) { map = new HashMap<>(); for (String s : dictionary) { String abbr = getAbbr(s); if (!map.containsKey(abbr)) { map.put(abbr, new HashSet<String>()); } map.get(abbr).add(s); } } public boolean isUnique(String word) { String abbr = getAbbr(word); if (!map.containsKey(abbr) || (map.get(abbr).contains(word) && map.get(abbr).size() == 1)) { return true; } return false; } private String getAbbr(String s) { if (s.length() < 3) { return s; } int len = s.length(); return s.substring(0, 1) + (len - 2) + s.substring(len - 1); } }
Python:
class ValidWordAbbr(object): def __init__(self, dictionary): """ initialize your data structure here. :type dictionary: List[str] """ self.lookup_ = collections.defaultdict(set) for word in dictionary: abbr = self.abbreviation(word) self.lookup_[abbr].add(word) def isUnique(self, word): """ check if a word is unique. :type word: str :rtype: bool """ abbr = self.abbreviation(word) return self.lookup_[abbr] <= {word} def abbreviation(self, word): if len(word) <= 2: return word return word[0] + str(len(word)-2) + word[-1]
C++:
// Time: ctor: O(n), n is number of words in the dictionary. // lookup: O(1) // Space: O(k), k is number of unique words. class ValidWordAbbr { public: ValidWordAbbr(vector<string> &dictionary) { for (string& word : dictionary) { const string abbr = abbreviation(word); lookup_[abbr].emplace(word); } } bool isUnique(string word) { const string abbr = abbreviation(word); return lookup_[abbr].empty() || (lookup_[abbr].count(word) == lookup_[abbr].size()); } private: unordered_map<string, unordered_set<string>> lookup_; string abbreviation(const string& word) { if (word.length() <= 2) { return word; } return word.front() + to_string(word.length()) + word.back(); } };
All LeetCode Questions List 题目汇总