LC 820. Short Encoding of Words

Given a list of words, we may encode it by writing a reference string S and a list of indexes A.

For example, if the list of words is ["time", "me", "bell"], we can write it as S = "time#bell#" and indexes = [0, 2, 5].

Then for each index, we will recover the word by reading from the reference string from that index until we reach a "#" character.

What is the length of the shortest reference string S possible that encodes the given words?

Example:

Input: words = ["time", "me", "bell"]
Output: 10
Explanation: S = "time#bell#" and indexes = [0, 2, 5].

 

Note:

  1. 1 <= words.length <= 2000.
  2. 1 <= words[i].length <= 7.
  3. Each word has only lowercase letters.

 

 

Runtime: 72 ms, faster than 65.22% of C++ online submissions for Short Encoding of Words.

 

#include <vector>
#include <string>
#include <algorithm>
using namespace std;

struct TrieNode {
  string word;
  TrieNode* children[26];
  TrieNode(){
    for(int i=0; i<26; i++) {
      children[i] = nullptr;
    }
  }
};

class Trie {
public:
  TrieNode* root;
  void buildTrie(vector<string> words){
    root = new TrieNode();
    for(auto w : words) {
      TrieNode* tmproot = root;
      for(int i=w.size()-1; i>=0; i--) {
        int idx = w[i] - 'a';
        if(!tmproot->children[idx]) {
          tmproot->children[idx] = new TrieNode();
        }
        tmproot = tmproot->children[idx];
      }
      tmproot->word = w;
    }
  }
};


class Solution {
public:
  int minimumLengthEncoding(vector<string>& words) {
    Trie trie = Trie();
    trie.buildTrie(words);
    TrieNode* root = trie.root;
    vector<string> ret;
    getroot2leaflength(root, ret);
    int val = 0;
    for(int i=0; i<ret.size(); i++) {
      val += ret[i].size() + 1;
    }
    return val;
  }
  void getroot2leaflength(TrieNode* root, vector<string>& ret) {
    bool leaf = true;
    for(int i=0; i<26; i++) {
      if(root->children[i]) {
        leaf = false;
        getroot2leaflength(root->children[i], ret);
      }
    }
    if(leaf) ret.push_back(root->word);
  }
};

 

 

 

 

 

 

posted @ 2019-01-19 17:48  yuxihong  阅读(218)  评论(0编辑  收藏  举报