【题目描述】
单词数组 words
的 有效编码 由任意助记字符串 s
和下标数组 indices
组成,且满足:
-
words.length == indices.length
- 助记字符串
s
以 '#'
字符结尾 - 对于每个下标
indices[i]
,s
的一个从 indices[i]
开始、到下一个 '#'
字符结束(但不包括 '#'
)的 子字符串 恰好与 words[i]
相等
给你一个单词数组 words
,返回成功对 words
进行编码的最小助记字符串 s
的长度 。
https://leetcode.cn/problems/short-encoding-of-words/
【示例】
【代码】存储后缀
很巧妙的思路
package com.company;
import java.util.*;
// 2023-03-01
class Solution {
public int minimumLengthEncoding(String[] words) {
List<String> list = Arrays.asList(words);
Set<String> set = new HashSet<>(list);
System.out.println("去重前: " + set);
// 删除words中可能重复的字符
for (String x: words){
for (int i = 1; i < x.length(); i++){
set.remove(x.substring(i));
}
}
System.out.println("去重后: " + set);
int res = 0;
for (String x : set){
res += x.length() + 1;
}
System.out.println("res: " + res);
return res;
}
}
public class Test {
public static void main(String[] args) {
new Solution().minimumLengthEncoding(new String[]{"time", "me", "bell"} ); // 输出:10
new Solution().minimumLengthEncoding(new String[]{"t"} ); // 输出:2
}
}
【代码】优解
package com.company;标签:String,minimumLengthEncoding,length,public,单词,LeeCode,words,new,820 From: https://blog.51cto.com/u_13682316/6094388
import java.util.*;
// 2023-03-01
class Solution {
public int minimumLengthEncoding(String[] words) {
// 先按字符串长度进行排序
Arrays.sort(words, (w1, w2) -> w2.length() - w1.length());
// 然后在进行匹配的计算
String sb = new String();
for (String word : words) {
if (!sb.contains(word + "#")) {
sb = sb.concat(word + "#");
}
}
System.out.println(sb);
return sb.length();
}
}
public class Test {
public static void main(String[] args) {
new Solution().minimumLengthEncoding(new String[]{"time", "me", "bell"} ); // 输出:10
new Solution().minimumLengthEncoding(new String[]{"t"} ); // 输出:2
}
}