Question
A valid encoding of an array of
wordsis any reference stringsand array of indicesindicessuch that:
words.length == indices.length- The reference string
sends with the'#'character.- For each index
indices[i], the substring ofsstarting fromindices[i]and up to (but not including) the next'#'character is equal towords[i].Given an array of
words, return the length of the shortest reference stringspossible of any valid encoding ofwords.
Solution 1
LeetCode这几天的每日一题时不让我学会字典树势不罢休啊……
字典树,参数isLeaf记录每个TireNode节点是否为叶子节点。
将单词倒序组建字典树,并维护isLeaf的属性。
计算从根节点到达每个叶子节点的长度再加一的和即可。
Code
1 | class Solution { |
Solution 2
排序,将数组words根据单词倒序排序。
倒序构成字典树,如果展开新的字典树分支(创建新的TrieNode节点)则将count加入根节点到新节点的距离。
Code
1 | class Solution { |
Solution 3
倒序重组字符串并记录到reversedWords[]数组,然后根据字典顺序排序。
如果数组的上一个字符串不是下一个字符串的前缀,则加入上一个字符串的长度加一。

Code
1 | class Solution { |
