• 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);
      }
    };
  • 相关阅读:
    拓端tecdat|R语言JAGS贝叶斯回归模型分析博士生延期毕业完成论文时间
    拓端tecdat|数据感知游客的森林公园游憩需求
    空间100%
    uniq -c 去掉重复行
    工作中实用的Shell脚本实例
    Linux下如何解压和压缩rar格式的包
    LRM-00109: could not open parameter file
    Xmanager5 Passive oracle图形化界面出来之后鼠标点不了
    谷歌浏览器请求返回JSON内容自动格式化
    JENKINS中创建全局变量并在JOB中使用
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10292659.html
Copyright © 2020-2023  润新知