-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path6. Short Encoding of Words
74 lines (60 loc) · 1.76 KB
/
6. Short Encoding of Words
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class Solution {
public int minimumLengthEncoding(String[] words) {
Arrays.sort(words,(a,b) -> b.length()-a.length());
StringBuilder encoding=new StringBuilder();
for(String s:words){
if(encoding.indexOf(s+"#")==-1){
encoding.append(s+"#");
}
}
return encoding.length();
}
}
class Solution {
public int minimumLengthEncoding(String[] words) {
Set<String> wordSet=new HashSet<>(Arrays.asList(words));
for(String s:words){
for(int i=1;i<s.length();i++){
wordSet.remove(s.substring(i));
}
}
int length=0;
for(String s:wordSet){
length+=s.length()+1;
}
return length;
}
}
class Solution {
public int minimumLengthEncoding(String[] words) {
Trie root=new Trie();
root.next=new Trie[26];
int length=0;
for(String s:words){
length += helper(s,root);
}
return length;
}
private int helper(String s,Trie node){
boolean newBranch=false;
int create=0;
for(int i=s.length()-1;i>=0;i--){
boolean newLevel = false;
int id = s.charAt(i)- 'a';
if(node.next==null){
newLevel =true;
node.next = new Trie[26];
}
if(node.next[id] == null){
if(newLevel==false) newBranch=true;
node.next[id]=new Trie();
create++;
}
node=node.next[id];
}
return newBranch?s.length()+1 : create;
}
class Trie{
Trie[] next=null;
}
}