暴力..
class Solution {
public int minimumLengthEncoding(String[] words) {
String[] temp = new String[words.length]; // 不能压缩的字符串集合
int size = 0, sum = 0;
boolean isEnd = false;
for (String s : words) {
isEnd = false;
for (int i = 0; i < size; i++) {
if (temp[i].endsWith(s)) { // 当前s属于一个已有的字符串的尾巴,啥事儿不干
isEnd = true;
break;
}
if (s.endsWith(temp[i])) { // 已有字符串是当前s的尾巴,s替换掉原来的值
sum = sum - temp[i].length() + s.length();
temp[i] = s;
isEnd = true;
break;
}
}
if (!isEnd) { // 是一个新的
temp[size++] = s;
sum += s.length() + 1;
}
}
return sum;
}
}
别人的方法1:
class Solution {
public int minimumLengthEncoding(String[] words) {
// 花式删除重复尾巴重复的
Set<String> set = new HashSet<>(Arrays.asList(words));
for (String s : words) {
for (int i = 1; i < s.length(); i++) {
set.remove(s.substring(i));
}
}
// 统计
int sum = 0;
for (String s : set) {
sum += s.length() + 1;
}
return sum;
}
}
别人的方法2:
class Solution {
public int minimumLengthEncoding(String[] words) {
// 从长到短的排序
Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());
// 然后计算
StringBuilder sb = new StringBuilder();
for (String s : words) {
if (!sb.toString().contains(s + "#")) {
sb.append(s).append("#");
}
}
return sb.length();
}
}
Trie 字典树:
class Solution {
public int minimumLengthEncoding(String[] words) {
int len = 0;
Trie trie = new Trie();
// 先对单词列表根据单词长度由长到短排序
Arrays.sort(words, (s1, s2) -> s2.length() - s1.length());
// 单词插入trie,返回该单词增加的编码长度
for (String word: words) {
len += trie.insert(word);
}
return len;
}
}
// 定义trie
class Trie {
TrieNode root;
public Trie() {
root = new TrieNode();
}
public int insert(String word) {
TrieNode cur = root;
boolean isNew = false;
// 倒着插入单词
for (int i = word.length() - 1; i >= 0; i--) {
int c = word.charAt(i) - 'a';
if (cur.children[c] == null) {
isNew = true; // 是新单词
cur.children[c] = new TrieNode();
}
cur = cur.children[c];
}
// 如果是新单词的话编码长度增加新单词的长度+1,否则不变。
return isNew? word.length() + 1: 0;
}
}
// 定义trie的节点
class TrieNode {
char val;
TrieNode[] children = new TrieNode[26];
public TrieNode() {}
public TrieNode(char val) {
this.val = val;
}
}