1. class Solution {
    2. class Trie{
    3. struct TrieNode{
    4. char val;
    5. TrieNode *children[26] = {0};//这里不初始化会报错
    6. TrieNode(char val){
    7. this->val = val;
    8. }
    9. };
    10. private:
    11. TrieNode *root;
    12. public:
    13. Trie(){
    14. root = new TrieNode(' ');
    15. }
    16. /** Inserts a word into the trie. */
    17. int insert(string word) {
    18. TrieNode *cur = root;
    19. bool isNew = false;
    20. for(int i = word.length() - 1;i >= 0 ;--i){
    21. char c = word[i];
    22. if(cur->children[c - 'a'] == nullptr){
    23. cur->children[c - 'a'] = new TrieNode(c);
    24. isNew = true;
    25. }
    26. cur = cur->children[c - 'a'];
    27. }
    28. if(isNew)return word.length() + 1;
    29. return 0;
    30. }
    31. };
    32. public:
    33. static bool compare(string s1, string s2){
    34. return s1.length() > s2.length();
    35. }
    36. int minimumLengthEncoding(vector<string>& words) {
    37. if(words.empty())return 0;
    38. Trie *trie = new Trie();
    39. sort(words.begin(), words.end(), compare);
    40. int len = 0;
    41. for(string word : words){
    42. len += trie->insert(word);
    43. }
    44. return len;
    45. }
    46. };