Tuesday, July 19, 2016

288. Unique Word Abbreviation

The key idea has bee explained in the code. When I revisited this problem, I made a mistake in line 26. I returned "mp[abbr].size() == 1 && mp[abbr].count(word) == 1". This is wrong because it should be true if the new word does not exist in the hashed set.

1:  class ValidWordAbbr {  
2:  private:  
3:    unordered_map<string, unordered_set<string>> dict;  
4:    bool flag;  
5:    string abbreviation(string word) {  
6:      if (word.size() <= 2) return word;  
7:      return word[0] + to_string(word.size()-2) + word[word.size()-1];  
8:    }  
9:  public:  
10:    ValidWordAbbr(vector<string> &dictionary) {  
11:      for (string s : dictionary) {  
12:        string abbr = abbreviation(s);  
13:        dict[abbr].insert(s);  
14:      }  
15:    }  
16:    bool isUnique(string word) {  
17:      string abbr = abbreviation(word);  
18:      // The idea is set up a hash table whose key is the abbreviation and value is the corresponding word set.  
19:      // We only get true when the word set only contains the input word.  
20:      // Case 1: FALSE, the word set donesn't contain the input word.  
21:      //     e.g. ["dog"]; isUnique("dig"). dict["d1g"].size() = 1 while dict["d1g"].count("dig") = 0.  
22:      // Case 2: TRUE, the word set only contains the input word.  
23:      //     e.g. ["dog"]; isUnique("dog"). dict["d1g"].size() = 1 while dict["d1g"].count("dog") = 1.  
24:      // Case 3: FALSE, the word set contains more than one word.  
25:      //     e.g. ["dog", "dig"]; isUnique("dog"). dict["d1g"].size() = 2 while dict["d1g"].count("dog") = 1.  
26:      return dict[abbr].size() == dict[abbr].count(word);  
27:    }  
28:  };  
29:  // Your ValidWordAbbr object will be instantiated and called as such:  
30:  // ValidWordAbbr vwa(dictionary);  
31:  // vwa.isUnique("hello");  
32:  // vwa.isUnique("anotherWord");  

No comments:

Post a Comment