/*
* 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;//只输出一种组合情况
}
}
}
}
}
Uva 10391 复合词
最新推荐文章于 2018-01-12 11:07:32 发布