题目:
给定一个单词列表,我们将这个列表编码成一个索引字符串 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
每个单词都是小写字母 。
解题思路:
1、字符串反转
2、对反转后的字符串排序
3、检查排序后的每一个单词,是否当前单词是下一个单词的前缀
代码实现:
class Solution {
public int minimumLengthEncoding(String[] words) {
int len = words.length;
int j = 0, ans = 0;
String[] reverseWords = new String[len];
// 1、字符串反转
for (String s : words) {
String reverseWord = new StringBuilder(s).reverse().toString();
reverseWords[j++] = reverseWord;
}
// 2、反转后的字符串排序
Arrays.sort(reverseWords);
// 3、检查排序后的每一个单词,是否当前单词是下一个单词的前缀
for (int i = 0; i < len; i++) {
// 当前单词是下一个单词的前缀,排除此单词
if (i < len - 1 && reverseWords[i + 1].startsWith(reverseWords[i])) {
continue;
}
// 单词长度加一,因为每个单词编码后后面还需要跟一个 # 符号
ans += reverseWords[i].length() + 1;
}
return ans;
}
}