|
1 | 1 | class Solution {
|
2 | 2 | public:
|
3 | | - vector<string> wordsAbbreviation(vector<string>& dict) |
4 | | - { |
5 | | - int n = dict.size(); |
| 3 | + vector<string> wordsAbbreviation(vector<string>& words) |
| 4 | + { |
| 5 | + int n = words.size(); |
6 | 6 | vector<string>rets(n);
|
7 | | - unordered_set<int>Set; |
| 7 | + |
| 8 | + vector<int>Set; |
8 | 9 | for (int i=0; i<n; i++)
|
9 | | - Set.insert(i); |
| 10 | + Set.push_back(i); |
10 | 11 |
|
11 | 12 | int abbrNum = 1;
|
12 | 13 | while (1)
|
13 | 14 | {
|
14 | | - unordered_map<string,vector<int>>Map; |
15 | | - for (auto idx : Set) |
| 15 | + unordered_map<string, vector<int>> Map; |
| 16 | + |
| 17 | + for (int idx: Set) |
16 | 18 | {
|
17 | | - string abbr=getAbbr(dict[idx], abbrNum); |
| 19 | + string abbr = getAbbr(words[idx], abbrNum); |
18 | 20 | Map[abbr].push_back(idx);
|
19 | 21 | }
|
20 | 22 | Set.clear();
|
21 | 23 |
|
22 | | - for (auto& [str, indices]:Map) |
| 24 | + for (auto& [abbr, indices]:Map) |
23 | 25 | {
|
24 | | - if (indices.size()>1) |
| 26 | + if (indices.size() > 1) |
25 | 27 | {
|
26 | 28 | for (int idx: indices)
|
27 | | - Set.insert(idx); |
28 | | - } |
| 29 | + Set.push_back(idx); |
| 30 | + } |
29 | 31 | else
|
30 | | - { |
31 | | - rets[indices[0]] = str; |
32 | | - } |
| 32 | + rets[indices[0]] = abbr; |
33 | 33 | }
|
34 | 34 |
|
35 | | - if (Set.size()==0) break; |
36 | | - abbrNum++; |
| 35 | + abbrNum += 1; |
| 36 | + if (Set.size() == 0) |
| 37 | + break; |
37 | 38 | }
|
38 | 39 |
|
39 | 40 | return rets;
|
40 | | - |
41 | 41 | }
|
42 | 42 |
|
43 | 43 | string getAbbr(string s, int abbrNum)
|
44 | | - { |
| 44 | + { |
| 45 | + if (s.size() < 3) return s; |
| 46 | + |
45 | 47 | string t;
|
46 | | - if (s.size()<=2) |
47 | | - { |
48 | | - t=s; |
49 | | - return t; |
50 | | - } |
| 48 | + t = s.substr(0, abbrNum); |
| 49 | + t += to_string(s.size() - abbrNum - 1); |
| 50 | + t += s.back(); |
| 51 | + |
| 52 | + if (t.size() == s.size()) return s; |
51 | 53 |
|
52 | | - t=s.substr(0, abbrNum); |
53 | | - t+=to_string(s.size()-abbrNum-1); |
54 | | - t+=s.back(); |
55 | | - if (t.size()==s.size()) t=s; |
56 | | - return t; |
| 54 | + return t; |
57 | 55 | }
|
58 | 56 | };
|
0 commit comments