HDU1247(字典树应用)

题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=1247

 

package D0726;
//字典树
import java.io.*;
public class HDU1247 {
	static Trie2 root = new Trie2();
	public static void main(String[] args) throws IOException {

		StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
		PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
		String str;
		String[] strarr = new String[50001];//保存得单词
		int index = 0;
		
		while(st.nextToken() != StreamTokenizer.TT_EOF){
			str = st.sval;
			strarr[index++] = str;
			insert(str);
		//	if(index==5)break;
		}
		//查找
		for(int i = 0;i<index;i++){
			if(find(strarr[i]))
				//System.out.println(strarr[i]);
				out.println(strarr[i]);
		}out.flush();
	}
	private static boolean find(String string) {
		Trie2 cur = root;
		for(int k = 0;k<string.length();k++){
			char ch = string.charAt(k);
			int idx = ch - 'a';
			cur = cur.child[idx];
			if(cur != null){
				if(cur.i==1&&find2(string.substring(k+1)))
					return true;
				
			}else return false;
		}
		return false;
	}
	private static boolean find2(String string) {
		Trie2 cur = root;
		for(int k = 0;k<string.length();k++){
			char ch = string.charAt(k);
			int idx = ch - 'a';
			if(cur.child[idx] != null){
				cur = cur.child[idx];
				if(cur.i==1&&k==(string.length()-1))//这个条件很重要,一定要比较到结尾
					return true;
				
			}else return false;
		}
		return false;
	}
	//构建字典树
	public static void insert(String str){
		Trie2 cur = root;
		for(char ch: str.toCharArray()){
			int idx = ch-'a';
			if (cur.child[idx] == null) {
				cur.child[idx] = new Trie2();
				cur = cur.child[idx];
			}else cur = cur.child[idx];
		}
		cur.i = 1;
	}
}
//字典树
class Trie2{
	Trie2[] child;
	int i;
	public Trie2(){
		child = new Trie2[26];
	}
	
}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

怎么演

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值