64,282
社区成员
发帖
与我相关
我的任务
分享
import java.util.Vector;
public class Demo {
//存储数据
private Vector<Vector<String>> Data;
public Demo() {
Data = new Vector<Vector<String>>();
}
//设置word1和word2为近义词
public boolean set(String word1, String word2) {
if (word1 == word2) {
return false;
}
int index1 = find(word1);
int index2 = find(word2);
if (index1 == -1 && index2 == -1) {
//两个都不在数据库中的情况
Vector<String> temp = new Vector<String>();
temp.add(word1);
temp.add(word2);
Data.add(temp);
}
else if (index1 != -1 && index2 == -1) {
//只有一个在数据库中1
Data.elementAt(index1).add(word2);
}
else if (index1 == -1 && index2 != -1) {
//只有一个在数据库中2
Data.elementAt(index2).add(word1);
}
else {
//两个都在数据库中
if (index1 != index2) {
//两个不在一行,则把index2中的数据合并到index1中
Vector<String> temp = Data.elementAt(index2);
for (int i = 0; i < temp.size(); i++) {
Data.elementAt(index1).add(temp.elementAt(i));
}
Data.remove(index2);
}
}
return true;
}
//判断word1和word2是否为近义词
public boolean is(String word1, String word2) {
if (word1 == word2) {
return true;
}
int index1 = find(word1);
int index2 = find(word2);
if (index1 == index2 && index1 != -1) {
return true;
}
return false;
}
//清除关系
public void clear() {
Data.clear();
}
// 在数据库中查找str在哪一行
private int find(String str) {
int ret = -1;
for (int i = 0; i < Data.size(); i++) {
Vector<String> temp = Data.elementAt(i);
for (int j = 0; j < temp.size(); j++) {
if (temp.elementAt(j) == str) {
return i;
}
}
}
return ret;
}
public static void main(String args[]) {
Demo a = new Demo();
a.set("a", "b");
a.set("c", "d");
a.set("b", "c");
System.out.print(a.is("a", "d"));
a.clear();
}
}