Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 12149 Accepted Submission(s): 4338
package 字典树; import java.util.Scanner; class Trie{ private Node root; public Trie() { root = new Node(); } public void insert(String s){ Node t =root; for(int i=0;i<s.length();i++){ if(t.nodes[s.charAt(i)-‘a‘]==null){ Node node = new Node(); t.nodes[s.charAt(i)-‘a‘] = node; } t = t.nodes[s.charAt(i)-‘a‘]; } t.isword = true; } public boolean find(String str){ Node t = root; for(int i=0;i<str.length();i++){ if(t.nodes[str.charAt(i)-‘a‘]!=null){ if(t.isword){ String str1 = str.substring(i, str.length()); //System.out.println(str1); if(find2(str1)){ return true; } } t = t.nodes[str.charAt(i)-‘a‘]; } else return false; } return false; } private boolean find2(String str) { Node t = root; for(int i=0;i<str.length();i++){ if(t.nodes[str.charAt(i)-‘a‘]==null){ return false; } t = t.nodes[str.charAt(i)-‘a‘]; } if(t.isword) return true; return false; } public class Node { Node [] nodes; boolean isword; //标记末尾 public Node() { isword = false; nodes = new Node[26]; } } } public class hdu_1247 { public static void main(String[] args) { Scanner sc =new Scanner(System.in); Trie t = new Trie(); String [] str = new String [50005]; int k=0; while(sc.hasNext()) { str[k] = new String(); str[k] = sc.next(); t.insert(str[k++]); } for(int i=0;i<k;i++){ if(t.find(str[i])){ System.out.println(str[i]); } } } }
原文:http://www.cnblogs.com/liyinggang/p/5303032.html