題目要求:
一、近義詞維護 給定接口,設置兩個單詞相互近義。近義詞具有相互傳遞性,如果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 }