标签:
题目要求:
一、近义词维护 给定接口,设置两个单词相互近义。近义词具有相互传递性,如果A和B为近义词,B和C是近义词,那么A、B、C都为近义词。要求提供接口,查询给定的两个但是是否是近义词关系。并且能提供接口清除所有的近义词关系。 接口说明 /** * 设置2个单词为近义词 * @param word1 单词一 * @param word2 单词二 * @return 0为成功,-1为失败或其他异常 */ public int setSynonyms(String word1, String word2) /** *判断2个单词是否为近义词(同一单词视为近义词) *@param word1 单词一 *@param word2 单词二 *@return 为近义词返回true,否则返回false */ public boolean isSynonyms(String word1, String word2) /** * 清除单词之间的近义词关系 */ public void clearRelations()
程序如下:首先设定A与B的近义词关系,再设定B与C的近义词关系,B与C以及A与C之间都是近义词关系,所以前两次为true,当执行clear方法后,map清空,最后一次打印为false
1 import java.util.HashMap; 2 import java.util.Iterator; 3 import java.util.Map; 4 import java.util.Scanner; 5 public class Synonyms { 6 private static Boolean isSyn = false; 7 static Map<String, String> map = new HashMap<String, String>(); 8 public static void main(String[] args) { 9 Scanner scan = new Scanner(System.in); 10 String line = scan.nextLine(); 11 String[] str = line.split(" "); 12 System.out.println(setSynonyms(str[0], str[1])); 13 String line2 = scan.nextLine(); 14 String[] str2 = line2.split(" "); 15 System.out.println(setSynonyms(str2[0], str2[1])); 16 System.out.println(isSynonyms(str2[0], str2[1])); 17 System.out.println(isSynonyms(str[0], str2[1])); 18 clearRelations(); 19 System.out.println(isSynonyms(str2[0], str2[1])); 20 scan.close(); 21 } 22 23 public static int setSynonyms(String word1, String word2) { 24 map.put(word1, word2); 25 map.put(word2, word1); 26 27 if (word1 != "" & word2 != "") { 28 // isSyn = true; 29 return 0; 30 } else 31 return -1; 32 33 } 34 35 public static boolean isSynonyms(String word1, String word2) { 36 if (!map.containsKey(word1)) { 37 isSyn = false; 38 } 39 if (map.containsKey(word1)) { 40 for (String key : map.keySet()) { 41 for (int i = 0; i < key.length(); i++) { 42 String value = map.get(word1); 43 String value2 = map.get(value); 44 if (value2.equals(word2)) { 45 isSyn = true; 46 } else if (word2.equals(map.get(word1))) 47 isSyn = true; 48 } 49 } 50 51 } else 52 isSyn = false; 53 return isSyn; 54 } 55 56 public static void clearRelations() { 57 Iterator it = map.keySet().iterator(); 58 String key = null; 59 while (it.hasNext()) { 60 key = it.next().toString(); 61 it.remove(); 62 63 } 64 } 65 }
标签:
原文地址:http://www.cnblogs.com/crows/p/4711444.html