[hihoCoder]1014 Trie水题

时间:2024-06-28 16:36:08

最最最最最最最基本的Trie词频统计应用了.

package trie;

import java.util.Scanner;

public class Main {

    public static void main( String[] args ) {
TrieTree tt = new TrieTree();
Scanner sc = new Scanner( System.in );
while(sc.hasNext()){
int n = sc.nextInt();
for(int i=0;i<n;i++){
tt.insert( sc.next() );
}
int m = sc.nextInt();
for(int i=0;i<m;i++){
tt.query( sc.next() );
}
}
}
} class TrieTree { public Node root; public TrieTree() {
root = new Node();
} public void insert( String word ) {
if( this.root == null || word == null || word.isEmpty() )
return;
int i = 0;
Node p = this.root;
while( i < word.length() ) {
if( p.node[ word.charAt( i ) - 'a' ] == null ) {
p.node[ word.charAt( i ) - 'a' ] = new Node( word.charAt( i ) );
p.node[ word.charAt( i ) - 'a' ].count++;
p = p.node[ word.charAt( i ) - 'a' ];
} else {
p.node[ word.charAt( i ) - 'a' ].count++;
p = p.node[ word.charAt( i ) - 'a' ];
}
i++;
}
} public boolean query( String word ) {
if( word.isEmpty() || word == null )
return false;
Node p = this.root;
int i = 0;
int ret = 0;
while( i < word.length() ) {
if( p.node[ word.charAt( i ) - 'a' ] == null ) {
ret = 0;
System.out.println( ret );
return false;
} else {
ret = p.node[ word.charAt( i ) - 'a' ].count;
p = p.node[ word.charAt( i ) - 'a' ];
}
i++;
}
System.out.println( ret );
return true;
}
} class Node { public static final int MAX_NODE = 26; public Node[] node = new Node[ MAX_NODE ]; public char data; public int count = 0; public Node() { } public Node( char data ) {
this.data = data;
}
}

样例输入

5
babaab
babbbaaaa
abba
aaaaabaa
babaababb
5
babb
baabaaa
bab
bb
bbabbaab

样例输出

1
0
3
0
0