public String longestCommonPrefix(String q, String[] strs) { if (strs == null || strs.length == 0) return""; if (strs.length == 1) return strs[0]; Trietrie=newTrie(); for (inti=1; i < strs.length ; i++) { trie.insert(strs[i]); } return trie.searchLongestPrefix(q); }
classTrieNode {
// R links to node children private TrieNode[] links;
privatefinalintR=26;
privateboolean isEnd;
// number of children non null links privateint size; publicvoidput(char ch, TrieNode node) { links[ch -'a'] = node; size++; }
publicintgetLinks() { return size; } //assume methods containsKey, isEnd, get, put are implemented as it is described //in https://leetcode.com/articles/implement-trie-prefix-tree/) }
publicclassTrie {
private TrieNode root;
publicTrie() { root = newTrieNode(); }
//assume methods insert, search, searchPrefix are implemented as it is described //in https://leetcode.com/articles/implement-trie-prefix-tree/) private String searchLongestPrefix(String word) { TrieNodenode= root; StringBuilderprefix=newStringBuilder(); for (inti=0; i < word.length(); i++) { charcurLetter= word.charAt(i); if (node.containsKey(curLetter) && (node.getLinks() == 1) && (!node.isEnd())) { prefix.append(curLetter); node = node.get(curLetter); } else return prefix.toString();