[hihoCoder]1014 Trie水题
2016-01-05 15:48
429 查看
最最最最最最最基本的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
相关文章推荐
- Instance Six:使用Prepared statements执行查询(更安全方便)
- Selenium-Grid 实现案列
- 中介者模式
- 典型Top K算法
- Java 生成本文文件的时候,Dos格式转成Unix格式
- linux本机root账户无法登录,但是远程ssh可登录
- UIBootatrap:是由AngularJS UI团队编写的纯AngularJS实现的Bootstrap组件
- Cocos2d-x V3.2+Cocos Studio1.6 实现一个简单的uibutton点击功能
- 手机端解决onkeyup事件
- Tomcat服务器下部署项目几种方式
- 解决Linux服务器 FIN_WAIT2 连接过多的问题
- 十步完全理解SQL
- 转载:寒门再难出贵子
- leetcode-Consecutive numbers
- Coldfusion8 读取HASH工具
- iOS9的http请求问题
- pixel像素与物理像素
- Android ActionBar 讲解
- vs2010编译lua-5.3.2
- Qt在Windows下的三种编程环境搭建