1. 程式人生 > 其它 >leetcode 820. 單詞的壓縮編碼

leetcode 820. 單詞的壓縮編碼

單詞陣列words 的 有效編碼 由任意助記字串 s 和下標陣列 indices 組成,且滿足:

words.length == indices.length
助記字串 s 以 '#' 字元結尾
對於每個下標 indices[i] ,s 的一個從 indices[i] 開始、到下一個 '#' 字元結束(但不包括 '#')的 子字串 恰好與 words[i] 相等
給你一個單詞陣列words ,返回成功對 words 進行編碼的最小助記字串 s 的長度 。

示例 1:

輸入:words = ["time", "me", "bell"]
輸出:10
解釋:一組有效編碼為 s = "time#bell#" 和 indices = [0, 2, 5] 。
words[0] = "time" ,s 開始於 indices[0] = 0 到下一個 '#' 結束的子字串,如加粗部分所示 "time#bell#"
words[1] = "me" ,s 開始於 indices[1] = 2 到下一個 '#' 結束的子字串,如加粗部分所示 "time#bell#"
words[2] = "bell" ,s 開始於 indices[2] = 5 到下一個 '#' 結束的子字串,如加粗部分所示 "time#bell#"
示例 2:

輸入:words = ["t"]
輸出:2
解釋:一組有效編碼為 s = "t#" 和 indices = [0] 。

提示:

1 <= words.length <= 2000
1 <= words[i].length <= 7
words[i] 僅由小寫字母組成

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

1:先把words中的字元都反轉。

2:把words中的字串排序。

3:從後往前遍歷,若第i個字串和 i + 1個字串的前部分一樣,則說明 i + 1覆蓋了 i,則不用操作。

4:否則 計數器加上 i字串的長度 ,再加上 1個 ‘#’的長度。

    public int minimumLengthEncoding(String[] words) {
        int length = words.length;
        for (int i = 0; i < length; i++) {
            words[i] = new StringBuilder(words[i]).reverse().toString();
        }
        Arrays.sort(words);
        int n = words[length - 1].length() + 1;
        
for (int i = length - 2; i >= 0; i--) { String word = words[i]; String word1 = words[i + 1]; if (word.length() > word1.length()) { n = n + word.length() + 1; } else { if (!word.equals(words[i + 1].substring(0, word.length()))) { n = n + word.length() + 1; } } } return n; }