由数据范围可知一个单词最多含有 7 个后缀,所以我们可以枚举单词所有的后缀。对于每个后缀,如果其存在 words 列表中,我们就将其从列表中删除。为了高效删除,我们将 words 用哈希集合来存储。
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publicintminimumLengthEncoding(String[] words) { Set<String> good = newHashSet<String>(Arrays.asList(words)); for (String word: words) { for (intk=1; k < word.length(); ++k) { good.remove(word.substring(k)); } }
intans=0; for (String word: good) { ans += word.length() + 1; } return ans; } }
[sol1-Python3]
1 2 3 4 5 6 7 8
classSolution: defminimumLengthEncoding(self, words: List[str]) -> int: good = set(words) for word in words: for k inrange(1, len(word)): good.discard(word[k:])
returnsum(len(word) + 1for word in good)
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { public: intminimumLengthEncoding(vector<string>& words){ unordered_set<string> good(words.begin(), words.end()); for (const string& word: words) { for (int k = 1; k < word.size(); ++k) { good.erase(word.substr(k)); } }
int ans = 0; for (const string& word: good) { ans += word.size() + 1; } return ans; } };
for (inti=0; i < words.length; ++i) { Stringword= words[i]; TrieNodecur= trie; for (intj= word.length() - 1; j >= 0; --j) { cur = cur.get(word.charAt(j)); } nodes.put(cur, i); }
intans=0; for (TrieNode node: nodes.keySet()) { if (node.count == 0) { ans += words[nodes.get(node)].length() + 1; } } return ans;
} }
classTrieNode { TrieNode[] children; int count;
TrieNode() { children = newTrieNode[26]; count = 0; }
public TrieNode get(char c) { if (children[c - 'a'] == null) { children[c - 'a'] = newTrieNode(); count++; } return children[c - 'a']; } }
[sol2-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution: defminimumLengthEncoding(self, words: List[str]) -> int: words = list(set(words)) #remove duplicates #Trie is a nested dictionary with nodes created # when fetched entries are missing Trie = lambda: collections.defaultdict(Trie) trie = Trie()
#reduce(..., S, trie) is trie[S[0]][S[1]][S[2]][...][S[S.length - 1]] nodes = [reduce(dict.__getitem__, word[::-1], trie) for word in words]
#Add word to the answer if it's node has no neighbors returnsum(len(word) + 1 for i, word inenumerate(words) iflen(nodes[i]) == 0)