leetcode 527 - Word Abbreviation

https://leetcode.com/problems/word-abbreviation/

Given an array of n distinct non-empty strings, you need to generate minimal possible abbreviations for every word following rules below.

Begin with the first character and then the number of characters abbreviated, which followed by the last character.
If there are any conflict, that is more than one words share the same abbreviation, a longer prefix is used instead of only the first character until making the map from word to abbreviation become unique. In other words, a final abbreviation cannot map to more than one original words.
If the abbreviation doesn’t make the word shorter, then keep it as original.
Example:
Input: [“like”, “god”, “internal”, “me”, “internet”, “interval”, “intension”, “face”, “intrusion”]
Output: [“l2e”,”god”,”internal”,”me”,”i6t”,”interval”,”inte4n”,”f2e”,”intr4n”]
Note:
Both n and the length of each word will not exceed 400.
The length of each word is greater than 1.
The words consist of lowercase English letters only.
The return answers should be in the same order as the original array.

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/* Time Limit Exceeded */
class Solution {
public:
struct Node {
vector<Node *> child;
int count;

Node() {
child.resize(256, nullptr);
count = 0;
}
};

void insert(Node *root, string &word) {
Node *node = root;

for (int c : word) {
if (node->child[c] == nullptr)
node->child[c] = new Node;
node = node->child[c];
node->count++;
}
}

string get_abbr(Node *root, string &word) {
Node *node = root;
int i = 0;

for (int c : word) {
node = node->child[c];
i++;
if (node->count == 1)
break;
}

int size = word.size();
if (i + 2 >= size)
return word;
else {
string abbr = word.substr(0, i);
abbr += to_string(size-i-1);
abbr.push_back(word.back());
return abbr;
}
}

void free_tree(Node *root) {
if (!root) return;

for (auto &node : root->child)
free_tree(node);

delete root;
}

vector<string> wordsAbbreviation(vector<string>& dict) {
unordered_map<string, vector<string>> maps;

for (auto &word : dict) {
string key = to_string(word.size());
key.push_back(word.back());

maps[key].push_back(word);
}

unordered_map<string, string> abbr_map;

for (auto &m : maps) {
Node *root = new Node;

for (auto &word : m.second)
insert(root, word);

for (auto &word : m.second)
abbr_map[word] = get_abbr(root, word);

free_tree(root);
}

vector<string> results;
for (auto &word : dict)
results.push_back(abbr_map[word]);

return results;
}
};