-
Notifications
You must be signed in to change notification settings - Fork 5
/
ShortestEncoding.java
89 lines (79 loc) · 2.25 KB
/
ShortestEncoding.java
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*https://leetcode.com/problems/short-encoding-of-words/*/
class TrieNode
{
TrieNode[] hash;
boolean isEndOfWord;
TrieNode()
{
hash = new TrieNode[26];
isEndOfWord = false;
}
}
class Trie
{
TrieNode root;
Trie()
{
root = new TrieNode();
}
public void add(String s)
{
TrieNode temp = root;
for (int i = 0; i < s.length(); ++i)
{
if (temp.hash[s.charAt(i)-'a'] == null)
temp.hash[s.charAt(i)-'a'] = new TrieNode();
temp = temp.hash[s.charAt(i)-'a'];
}
temp.isEndOfWord = true;
}
public boolean contains(String s)
{
TrieNode temp = root;
for (int i = 0; i < s.length(); ++i)
{
if (temp.hash[s.charAt(i)-'a'] != null)
temp = temp.hash[s.charAt(i)-'a'];
else return false;
}
return temp.isEndOfWord;
}
}
class Solution {
public int minimumLengthEncoding(String[] words) {
//sort the array according to the length of words in descending order
Arrays.sort(words,new Comparator<String>(){
public int compare(String s1, String s2)
{
return s2.length()-s1.length();
}
});
//create a trie
Trie trie = new Trie();
StringBuffer result = new StringBuffer("");
//for each word
for (int i = 0; i < words.length; ++i)
{
//if trie already contains the word then continue
if (trie.contains(words[i]))
continue;
StringBuffer sb = new StringBuffer("");
//for each character in reverse order
for (int j = words[i].length()-1; j >= 0; --j)
{
//append it at the front of the stringbuffer
StringBuffer temp = new StringBuffer("");
temp.append(words[i].charAt(j));
temp.append(sb);
sb = temp;
//add it to trie
trie.add(sb.toString());
}
//append the word to result along with #
result.append(words[i]);
result.append("#");
}
//return its length
return result.length();
}
}