題目連結
題意:
字典翻譯對照,測資前半每行以空格區別語言 A 與 B,
後半每行為語言B的文字,要輸出對應的語言 A 文字
A 與 B的文字都由一個單字組成(不含空白的英文字母序列)
若找不到對應的 A ,輸出 eh
解法:
透過 HashMap,Key - Value配對
put(Key, Value) 方法放資料
get(Key) 方法以參數 Key 取得回傳值 Value
containsKey(Key) 方法判斷是否存在該 Key - Value
因為題目要以 B 搜尋 A,HashMap 的 get 參數為 Key
所以我把 A 當作 Value,B當作 Key 實作
程式(Java):
題意:
字典翻譯對照,測資前半每行以空格區別語言 A 與 B,
後半每行為語言B的文字,要輸出對應的語言 A 文字
A 與 B的文字都由一個單字組成(不含空白的英文字母序列)
若找不到對應的 A ,輸出 eh
解法:
透過 HashMap,Key - Value配對
put(Key, Value) 方法放資料
get(Key) 方法以參數 Key 取得回傳值 Value
containsKey(Key) 方法判斷是否存在該 Key - Value
因為題目要以 B 搜尋 A,HashMap 的 get 參數為 Key
所以我把 A 當作 Value,B當作 Key 實作
程式(Java):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String args[]) { | |
Scanner sc = new Scanner(System.in); | |
String dic = ""; | |
HashMap<String, String> hm = new HashMap<String, String>(); | |
dic = sc.nextLine(); | |
while (sc.hasNextLine()) { | |
while (true) { | |
if (!dic.contains(" ")) | |
break; | |
String[] arr = dic.split(" "); | |
hm.put(arr[1], arr[0]); | |
dic = sc.nextLine(); | |
} | |
while (sc.hasNextLine()) { | |
String msg = sc.nextLine(); | |
if (!hm.containsKey(msg)) | |
System.out.println("eh"); | |
else | |
System.out.println(hm.get(msg)); | |
} | |
} | |
} | |
} |
留言
張貼留言