Java實現 LeetCode 820 單詞的壓縮編碼(暴力)

820. 單詞的壓縮編碼

給定一個單詞列表,我們將這個列表編碼成一個索引字符串 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
每個單詞都是小寫字母 。

class Solution {
    public int minimumLengthEncoding(String[] words) {
        int len = 0;
        Trie trie = new Trie();
        // 先對單詞列表根據單詞長度由長到短排序
        Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());
        // 單詞插入trie,返回該單詞增加的編碼長度
        for (String word: words) {
            len += trie.insert(word);
        }
        return len;
    }
}

// 定義tire
class Trie {
    
    TrieNode root;
    
    public Trie() {
        root = new TrieNode();
    }

    public int insert(String word) {
        TrieNode cur = root;
        boolean isNew = false;
        // 倒着插入單詞
        for (int i = word.length() - 1; i >= 0; i--) {
            int c = word.charAt(i) - 'a';
            if (cur.children[c] == null) {
                isNew = true; // 是新單詞
                cur.children[c] = new TrieNode();
            }
            cur = cur.children[c];
        }
        // 如果是新單詞的話編碼長度增加新單詞的長度+1,否則不變。
        return isNew? word.length() + 1: 0;
    }
}

class TrieNode {
    char val;
    TrieNode[] children = new TrieNode[26];

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