题目:
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
HashMap。
C++版:
class ValidWordAbbr { public: ValidWordAbbr(vector<string> &dictionary) { for(auto i : dictionary) { string key = i[0] + to_string(i.length() - 2) + i[i.length() - 1]; if(d.find(key) == d.end()) { vector<string> list; list.push_back(i); d.insert(pair<string, vector<string>>(key, list)); } else { d[key].push_back(i); } } } bool isUnique(string word) { string key = word[0] + to_string(word.length() - 2) + word[word.length() - 1]; if(d.find(key) == d.end()) return true; else if(d[key].size() == 1 && d[key][0] == word) return true; return false; } private: unordered_map<string, vector<string>> d; }; // Your ValidWordAbbr object will be instantiated and called as such: // ValidWordAbbr vwa(dictionary); // vwa.isUnique("hello"); // vwa.isUnique("anotherWord");
public class ValidWordAbbr { public ValidWordAbbr(String[] dictionary) { for(String s: dictionary) { String key = s.charAt(0) + Integer.toString(s.length() - 2) + s.charAt(s.length() - 1); if(d.containsKey(key)) { d.get(key).add(s); } else { List<String> l = new ArrayList<>(); l.add(s); d.put(key, l); } } } public boolean isUnique(String word) { String key = word.charAt(0) + Integer.toString(word.length() - 2) + word.charAt(word.length() - 1); if(!d.containsKey(key)) return true; else if(d.get(key).size() < 2 && d.get(key).get(0).equals(word)) return true; return false; } private HashMap<String, List<String>> d = new HashMap<>(); } // Your ValidWordAbbr object will be instantiated and called as such: // ValidWordAbbr vwa = new ValidWordAbbr(dictionary); // vwa.isUnique("Word"); // vwa.isUnique("anotherWord");
class ValidWordAbbr(object): def __init__(self, dictionary): """ initialize your data structure here. :type dictionary: List[str] """ self.d = collections.defaultdict(list) for i in dictionary: self.d[i[0] + str(len(i) - 2) + i[-1]].append(i) def isUnique(self, word): """ check if a word is unique. :type word: str :rtype: bool """ key = word[0] + str(len(word) - 2) + word[-1] if key not in self.d: return True elif len(self.d[key]) == 1 and self.d[key][0] == word: return True else: return False # Your ValidWordAbbr object will be instantiated and called as such: # vwa = ValidWordAbbr(dictionary) # vwa.isUnique("word") # vwa.isUnique("anotherWord")