标签:
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 131070/65535 K (Java/Others)
Total Submission(s): 29183 Accepted Submission(s): 11454
import java.util.Scanner; class Trie { private Node root; public Trie() { root = new Node(); } public void insert(String str){ Node t = root; for(int i=0;i<str.length();i++){ if(t.nodes[str.charAt(i)-‘a‘]==null){ Node node = new Node(); t.nodes[str.charAt(i)-‘a‘] = node; } t = t.nodes[str.charAt(i)-‘a‘]; t.num++; } } public int find(String str){ Node t = root; for(int i=0;i<str.length();i++){ if(t.nodes[str.charAt(i)-‘a‘]==null) return 0; t = t.nodes[str.charAt(i)-‘a‘]; } return t.num; } class Node{ int num; Node []nodes; public Node() { num= 0; nodes = new Node[26]; } } } public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Trie tree = new Trie(); while(true){ String str = sc.nextLine(); if(str.length()==0) break; tree.insert(str); } while(sc.hasNext()){ String str1 = sc.nextLine(); System.out.println(tree.find(str1)); } } }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5348050.html