# LeetCode_單詞的壓縮編碼_Array_M

820. 單詞的壓縮編碼

暴力..

``````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;
}
}``````

``````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;
}
}``````

``````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;
}
}``````