本文主要是介绍[LeetCode] 820. Short Encoding of Words,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题:https://leetcode.com/problems/short-encoding-of-words/
题目大意
参考题目
思路
set 集合
将所有word 放入set中,然后遍历所有set中的word,将word的从头的子串都从set中删除,最后统计 set中所有(word 的长度 + 1)(’#’)
class Solution {public int minimumLengthEncoding(String[] words) {Set<String> set = new HashSet(Arrays.asList(words));for(String word : words){for(int i = 1 ; i <word.length();i++){set.remove(word.substring(i));}}int res = 0;for(String word:set){res += word.length() +1;}return res;}
}
trie
将word翻转 插入 trie中。
最后统计tire 中所有 叶子的深度 + 1 (’#’)
class TrieNode{char ch;boolean isLeaf;TrieNode []nextNode = new TrieNode[26];public TrieNode(char cCh){ch = cCh;}
}
class Trie{TrieNode root;public Trie(){root = new TrieNode('?');}public void insert(String s){TrieNode curNode = root;for(int i = 0 ; i < s.length();i++){if(curNode.nextNode[s.charAt(i)-'a'] == null)curNode.nextNode[s.charAt(i)-'a'] = new TrieNode(s.charAt(i));curNode = curNode.nextNode[s.charAt(i)-'a'];}curNode.isLeaf = true;}
}
class Solution {int res = 0;public int minimumLengthEncoding(String[] words) {Trie trie = new Trie();for(String word:words){trie.insert((new StringBuilder(word)).reverse().toString());}calStringLen(trie.root,0);return res;}public void calStringLen(TrieNode root,int level){if(root == null)return;boolean isTreeLeaf = true;for(int i = 0 ; i < 26 ;i++){if(root.nextNode[i] != null){calStringLen(root.nextNode[i],level+1);isTreeLeaf = false;}}if(isTreeLeaf)res+=level+1;}
}
这篇关于[LeetCode] 820. Short Encoding of Words的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!