码迷,mamicode.com
首页 > 其他好文 > 详细

LC 820. Short Encoding of Words

时间:2019-01-19 18:56:28      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:ref   ati   case   encode   mes   size   and   style   color   

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);
  }
};

 

 

 

 

 

 

LC 820. Short Encoding of Words

标签:ref   ati   case   encode   mes   size   and   style   color   

原文地址:https://www.cnblogs.com/ethanhong/p/10292659.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!