leetcode820. 單詞的壓縮編碼

給定一個單詞列表,我們將這個列表編碼成一個索引字符串 S 與一個索引列表 A。

例如,如果這個列表是 [“time”, “me”, “bell”],我們就可以將其表示爲 S = “time#bell#” 和 indexes = [0, 2, 5]。

對於每一個索引,我們可以通過從字符串 S 中索引的位置開始讀取字符串,直到 “#” 結束,來恢復我們之前的單詞列表。

那麼成功對給定單詞列表進行編碼的最小字符串長度是多少呢?

示例:

輸入: words = ["time", "me", "bell"]
輸出: 10
說明: S = "time#bell#" , indexes = [0, 2, 5]

提示:

  • 1 <= words.length <= 2000
  • 1 <= words[i].length <= 7
  • 每個單詞都是小寫字母 。

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/short-encoding-of-words
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

完整代碼

又是一道讓我必須考慮到要認清題目本質的題目。
本質
統計單詞列表中一個單詞不是另一個單詞後綴的單詞的長度
基本思想
將後綴轉化成前綴

  • 將每一個單詞逆序
  • 將逆序後的單詞排序
  • 判斷相鄰的兩個單詞是否前一個是後一個的前綴
class Solution {
public:
    int minimumLengthEncoding(vector<string>& words) {
        if(words.size() == 0)
            return 0;
        for(auto &w : words)
            reverse(w.begin(), w.end());
        sort(words.begin(), words.end());
        int res = 0;
        for(int i = 0; i < words.size() - 1; ++i){
            
            if(words[i] != words[i + 1].substr(0, words[i].size()))
                res += words[i].size() + 1;
        }
        return res + words[words.size() - 1].size() + 1;
    }
};

字典樹

struct TrieNode{
    TrieNode * children[26] ;    
    TrieNode(){
        for(int i = 0; i < 26; ++i)
            children[i] = NULL;
    }
};
class Trie{
public:
    Trie(){
        root = new TrieNode();
    }
    int insert(string s){
        TrieNode * cur = root;
        bool isNew = false;
        int i;
        for(i = 0; i < s.length(); ++i){
            if(cur->children[s[i] - 'a'] == NULL){
                cur->children[s[i] - 'a'] = new TrieNode();
                isNew = true;
            }
            cur = cur->children[s[i] - 'a'];
        }
        return isNew ? i : 0;
    }
private:
    TrieNode * root;
};
class Solution {
public:
    int minimumLengthEncoding(vector<string>& words) {
        if(words.size() == 0)
            return 0;
        // 1.將單詞逆序
        for(auto &w : words)
            reverse(w.begin(), w.end());
        // 2.將單詞按照長短排序,長的在前,確保先插入的是長的
        sort(words.begin(), words.end(), cmp);
        // 3.將單詞插入到字典樹中
        Trie root;
        int res = 0;
        for(int i = 0; i < words.size(); ++i){
            int len = root.insert(words[i]);
            if(len)
                res += len + 1;
        }
        return res;
    }
private:
    static bool cmp(string s, string t){
        return s.length() > t.length();
    }

};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章