反转+排序
无需字典树,轻轻一反转,结果就出来(C++/Java/Python)
class Solution {
public:
int minimumLengthEncoding(vector<string>& words) {
int n=words.size();
vector<string> reversed_words;
for(string word:words){
/ 反转每个单词
reverse(word.begin(),word.end());
reversed_words.push_back(word);
}
/ 字典序排序
sort(reversed_words.begin(),reversed_words.end());
int res=0;
for(int i=0;i<n;i++){
if(i+1<n&&reversed_words[i+1].find(reversed_words[i])==0) ; / 当前单词是下一个单词的前缀,丢弃
else res+=reversed_words[i].length()+1; / 单词加上一个 '#' 的长度
}
return res;
}
};
字典树
99% Trie 吐血攻略,包教包会
手撕字典树(Trie 树) C++ 另附暴力哈希解法
https://leetcode-cn.com/problems/short-encoding-of-words/solution/dan-ci-de-ya-suo-bian-ma-by-leetcode-solution/
class TrieNode{
TrieNode* children[26];
public:
int count;
TrieNode() {
for (int i = 0; i < 26; ++i) children[i] = NULL;
count = 0;
}
TrieNode* get(char c) {
if (children[c - 'a'] == NULL) {
children[c - 'a'] = new TrieNode();
count++;
}
return children[c - 'a'];
}
};
class Solution {
public:
int minimumLengthEncoding(vector<string>& words) {
TrieNode* trie = new TrieNode();
unordered_map<TrieNode*, int> nodes;
for (int i = 0; i < (int)words.size(); ++i) {
string word = words[i];
TrieNode* cur = trie;
for (int j = word.length() - 1; j >= 0; --j)
cur = cur->get(word[j]);
nodes[cur] = i;
}
int ans = 0;
for (auto& [node, idx] : nodes) {
if (node->count == 0) {
ans += words[idx].length() + 1;
}
}
return ans;
}
};