Uva 10391 复合词

/*
 * UVa 10391 复合词
 * */
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.util.Scanner;

class CompoundWords {

	static final int SEED = 131;// 31,131,1313,13131,131313...
	static final int MAX = 1000003;// hash表长度
	static final int MAXSTATE = 120010;// 最多条目数
	int[] head = new int[MAX];
	int[] next = new int[MAXSTATE];
	String[] dic = new String[MAXSTATE]; // 存储单词

	private int BKDR_HASH(String s) {
		char[] chars = s.toCharArray();
		int hash = 0;
		for (int i = 0; i < chars.length; i++) {
			hash = hash * SEED + chars[i];
		}
		return Math.abs(hash % MAX);
	}

	private int isFound(String s) {
		int h = BKDR_HASH(s);
		int u = head[h];// 从表头开始查找
		while (u > 0) {
			if (dic[u].equals(s)) {// 找到返回u
				return u;
			}
			u = next[u];
		}
		return -1;
	}

	private boolean try_to_insert(int s) {
		int h = BKDR_HASH(dic[s]);
		int u = head[h];// 从表头开始查找
		while (u > 0) {
			if (dic[u].equals(dic[s]))// 如果已经存在插入失败
				return false;
			u = next[u];
		}
		next[s] = head[h];// 插入到链表中
		head[h] = s;
		return true;
	}
	
	public static void main(String[] args) throws Exception {
		CompoundWords cw = new CompoundWords();
		// 输入重定向
		BufferedInputStream in = new BufferedInputStream(new FileInputStream("cw.txt"));
		System.setIn(in);
		
		Scanner scanner = new Scanner(System.in);
		int position = 1;//从位置1开始插入到字典中
		while (scanner.hasNext()) {
			String s = scanner.nextLine();
			if (s.length() > 0) {
				cw.dic[position] = s;
				cw.try_to_insert(position++);
			} 
		}
		for(int i=1; i<position; i++) {//读取字典中每个单词
			String ss = cw.dic[i];
			for(int j=1; j<ss.length(); j++) {//将单词拆分
				String part1 = ss.substring(0, j);
				String part2 = ss.substring(j, ss.length());
				if(cw.isFound(part1)>=0 && cw.isFound(part2)>=0) {
					System.out.println(ss);
					break;//只输出一种组合情况
				}
			}
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值