import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.Stack; /** * Created by ${chixiu} on 17/11/10. */ public class TriedStr { public static void main(String[] args) { String[] worlds = new String[]{"d","do","dog","p","pe","pen","peng","pengu","pengui","penguin","e","el","ele","elep","eleph","elepha","elephan","elephant"}; longestWord(worlds); System.out.println("TriedStr.main "+longestWord(worlds)); } public static String longestWord(String[] words) { Node root = new Node(); int i=0; for(String sl :words){ sert( sl, i, root ); i++; } return findF(root,words); } static class Node{ int index=-1; Map<Character,Node> map = new HashMap<Character,Node>(); } public static String findF(Node root,String[] words){ Node cur = root; String ans=""; Stack<Node> stack = new Stack<>(); stack.push(cur); while(!stack.empty()){ Node node = stack.pop(); if(node == root){ for( Map.Entry<Character,Node> entrySet:node.map.entrySet()){ stack.push(entrySet.getValue()); } }else{ if(node.index <0){ continue; } String word = words[node.index]; if (word.length() > ans.length() || word.length() == ans.length() && word.compareTo(ans) < 0) { ans = word; } for( Map.Entry<Character,Node> entrySet:node.map.entrySet()){ if(entrySet.getValue().index <0){ continue; } stack.push(entrySet.getValue()); } } } return ans; } public static void sert(String str,int index,Node root ){ Node cur = root; for(Character character:str.toCharArray()){ Node node = cur.map.get(character); if( node == null){ node = new Node(); cur.map.put(character,node); } cur = node; } cur.index=index; } }