classSolution{publicintminimumLengthEncoding(String[] words){
String S ="";int len = words.length;
S += words[0]+"#";for(int i=1;i<len;i++){
String ss = words[i]+"#";if(S.indexOf(ss)==-1){
S += ss;}}
String SS ="";
SS += words[len-1]+"#";for(int i=len-2;i>=0;i--){
String ss = words[i]+"#";if(SS.indexOf(ss)==-1){
SS += ss;}}return Math.min(S.length(),SS.length());}}
题解做法1:记录单词后缀。
classSolution{publicintminimumLengthEncoding(String[] words){
Set<String> good =newHashSet(Arrays.asList(words));for(String word: words){for(int k =1; k < word.length();++k)
good.remove(word.substring(k));}int ans =0;for(String word: good)
ans += word.length()+1;return ans;}}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/short-encoding-of-words/solution/dan-ci-de-ya-suo-bian-ma-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解题做法2:字典树方法。
classSolution{publicintminimumLengthEncoding(String[] words){
TrieNode trie =newTrieNode();
Map<TrieNode, Integer> nodes =newHashMap();for(int i =0; i < words.length;++i){
String word = words[i];
TrieNode cur = trie;for(int j = word.length()-1; j >=0;--j)
cur = cur.get(word.charAt(j));
nodes.put(cur, i);}int ans =0;for(TrieNode node: nodes.keySet()){if(node.count ==0)
ans += words[nodes.get(node)].length()+1;}return ans;}}classTrieNode{
TrieNode[] children;int count;TrieNode(){
children =newTrieNode[26];
count =0;}public TrieNode get(char c){if(children[c -'a']== null){
children[c -'a']=newTrieNode();
count++;}return children[c -'a'];}}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/short-encoding-of-words/solution/dan-ci-de-ya-suo-bian-ma-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。