/**
* <pre>
* 近义词维护
*
* 给定接口,设置两个单词相互近义。
* 近义词具有相互传递性,如果A和B为近义词,B和C是近义词,那么A、B、C都为近义词。
* </pre>
*
*/
public class Demo
{
List<Set<String>> container = new ArrayList<Set<String>>();
/**
* 设置2个单词为近义词
*
* @param word1 单词一
* @param word2 单词二
* @return {@code 0}为成功,{@code -1}为失败或其他异常
*/
public int setSynonyms(String word1, String word2)
{
if (isEmpty(word1) || isEmpty(word1))
{
return -1;
}
boolean found = false;
for (int i = 0; i < container.size(); i++)
{
Set<String> set = container.get(i);
if (set.contains(word1))
{
set.add(word2);
found = true;
}
else if (set.contains(word2))
{
set.add(word1);
found = true;
}
}
if (!found)
{
Set<String> set = new HashSet<String>();
set.add(word1);
set.add(word2);
container.add(set);
}
return 0;
}
private boolean isEmpty(String word)
{
return word == null || word.isEmpty();
}
/**
* 判断2个单词是否为近义词(同一单词视为近义词)
*
* @param word1 单词一
* @param word2 单词二
* @return 为近义词返回{@code true},否则返回{@code false}
*/
public boolean isSynonyms(String word1, String word2)
{
if (isEmpty(word1) || isEmpty(word1))
{
return false;
}
if (word1.equals(word2))
{
return true;
}
boolean synonyms = false;
for (int i = 0; i < container.size(); i++)
{
Set<String> set = container.get(i);
if (set.contains(word1) && set.contains(word2))
{
synonyms = true;
break;
}
}
return synonyms;
}
/**
* 清除单词之间的近义词关系
*/
public void clearRelations()
{
container.clear();
}
public static void main(String[] args)
{
Demo d = new Demo();
d.setSynonyms("1", "0");
d.setSynonyms("2", "3");
d.setSynonyms("1", "5");
d.setSynonyms("6", "5");
//d.clearRelations();
System.out.println(d.isSynonyms("1", "0"));
}
}