LeetCode#288。ユニークな単語の略語



Leetcode 288 Unique Word Abbreviation



タイトル説明:

単語の省略形は、の形式に従います。以下は、単語の略語の例です。



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

辞書があり、単語が与えられていると仮定して、その略語が辞書内で一意であるかどうかを確認します。単語の略語は、ない場合は一意です その他 辞書の単語にも同じ略語があります。

例:



Given dictionary = [ 'deer', 'door', 'cake', 'card' ] isUnique('dear') -> false isUnique('cart') -> true isUnique('cane') -> false isUnique('make') -> true class ValidWordAbbr { public: ValidWordAbbr(vector& dictionary) { for(string& s:dictionary) dict[abbreviation(s)].insert(s) } bool isUnique(string word) { string s=abbreviation(word) // Either there is no such abbreviation in the dictionary, or there is only one word return dict[s].count(word)==dict[s].size() } string abbreviation(string& s) { if(s.size()>2) return s.front()+to_string(s.size()-2)+s.back() else return s } private: unordered_map dict }