近义词维护

/**
 * <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"));
 }
 
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值