LeetCode 820 Short Encoding of Words
题目分析
Given a list of words, we may encode it by writing a reference string
S
and a list of indexesA
.For example, if the list of words is
["time", "me", "bell"]
, we can write it asS = "time#bell#"
andindexes = [0, 2, 5]
.Then for each index, we will recover the word by reading from the reference string from that index until we reach a “#” character.
What is the length of the shortest reference string S possible that encodes the given words?
Example:
Input: words = ["time", "me", "bell"] Output: 10 Explanation: S = "time#bell#" and indexes = [0, 2, 5].
Note:
1 <= words.length <= 2000.
1 <= words[i].length <= 7.
- Each word has only lowercase letters.
题目有点难理解,不过看了例子之后还是很快理解了题目的意思,就是将一堆单词编码为一个字符串,使用给定的例子说明一下:
String[] words = {"time", "me", "bell"};
String S = "time#bell#";
int[] indexes = {0, 2, 5};
me
是time
的后缀,那么me
就可以直接使用time
表示,也即time#
,对应的index
就是2,而剩下的bell
不是别的单词的后缀,也没有别的单词是bell
的后缀,所以就是单独一个了。
再给一个示例
String[] words = {"time", "ti", "me"};
String S = "time#ti#";
int[] indexes = {0, 5, 2};
也很容易理解了吧。
题目要求的就是这个编码串的长度。
思考
我是用的暴力遍历所有字符串和其他字符串的关系,如果一个字符串是别的字符串的后缀那么就不需要将其添加到最终的字符串中,思路是没有错的,但是在第一次提交时得到了一个错误的提交,就是5个time
字符串的编码,按照我的思路最终长度是0,然而是必须要有一个字符串的,那么就先对数据进行去重处理就可以了,再进行遍历,最终完美AC。
代码实现
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
class Solution {
public int minimumLengthEncoding(String[] words) {
if (words == null || words.length == 0) {
return 1;
}
// 使用set对字符串去重
HashSet<String> strings = new HashSet<>();
// 添加数据,自动去重
Collections.addAll(strings, words);
Iterator<String> strs = strings.iterator();
int size = 0;
// 全部放入到原来的words中,其实新建一个大小为strings.size()的String数组是
// 个更好的选择,为了时间不管了,运行中也没有报错。幸好没有要求给出对应的下标数组
while (strs.hasNext()) {
words[size++] = strs.next();
}
int result = 0, add;
for (int i = 0; i < size; i++) {
// 表示本字符串可以给最终字符串增加的长度
add = words[i].length() + 1;
for (int j = 0; j < size; j++) {
// 如果这个字符串是别的字符串的后缀,那么这个字符串就可以用其表示
// 而不需要在主串后再加一段
if (i != j && words[j].endsWith(words[i])) {
add = 0;
break;
}
}
result += add;
}
return result;
}
}
感想
欢迎followGitHub。