0%

288. Unique Word Abbreviation

O(n) time O(n) space
纯粹考对题目理解和corner case想的全不全
题目isunique的定义:

  1. 词典里没有这个词的缩写
  2. 词典里有这个词的缩写,原词都是这个词(意味着词典里如果有缩写相同的词,则必须相同且只能是这个词,即不能有歧义,同一个缩写只能对应唯一的词)

需要考虑的corner case:

  1. 词典里有重复词
  2. 词典里有缩写一样的不同词

为了节省空间,用一个hashmap,key是缩写,value存该缩写的唯一的这个词,如果词典里有重复词则跳过,如果词典里有缩写一样的不同词则把value置空

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class ValidWordAbbr {
public:
ValidWordAbbr(vector<string>& dictionary) {
for (const auto &w : dictionary) {
const auto &a = norm(w);
if (m.count(a) == 0) { // 如果不存在这个词的缩写
m[a] = w;
} else if (!m[a].empty() && m[a] != w) { // 如果词典里有缩写一样的不同词
m[a].clear();
}
}
}

bool isUnique(string word) {
const auto a = norm(word);
return m.count(a) == 0 || m[a] == word; // 如果找不到该词的缩写或者能找到该词的缩写且是同一个词的缩写,则是unique的
}

string norm(const string &w) {
if (w.length() < 3) return w;
string res(1, w[0]);
res += to_string(w.length() - 2);
res += w.back();
return res;
}

unordered_map<string, string> m;
};

/**
* Your ValidWordAbbr object will be instantiated and called as such:
* ValidWordAbbr* obj = new ValidWordAbbr(dictionary);
* bool param_1 = obj->isUnique(word);
*/