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。