日期:2025年12月22日
ZeroJudge 題目連結:a135. 12250 - Language Detection
解題想法
用字典建對照表,先檢查輸入的字串是否在字典的 key 值之中,如果沒有就輸出 UNKNOWN,如果有就輸出表格中對應的 val。如果是 Python 的 dict,也可以用 dict.get(key, 預設值) 讀取表格中的資料。
Python 程式碼
使用時間約為 17 ms,記憶體約為 2.8 MB,通過測試。
lan = {"HELLO": "ENGLISH",
"HOLA": "SPANISH",
"HALLO": "GERMAN",
"BONJOUR": "FRENCH",
"CIAO": "ITALIAN",
"ZDRAVSTVUJTE": "RUSSIAN"}
ca = 0
while True:
s = input()
if s == "#": break
ca += 1
print(f"Case {ca:d}: ", end="")
if s not in lan:
print("UNKNOWN")
else:
print(lan[s])
使用時間約為 7 ms,記憶體約為 2.9 MB,通過測試。
import sys
lan = {"HELLO": "ENGLISH",
"HOLA": "SPANISH",
"HALLO": "GERMAN",
"BONJOUR": "FRENCH",
"CIAO": "ITALIAN",
"ZDRAVSTVUJTE": "RUSSIAN"}
result = []
lines = sys.stdin.readlines()
ca = 0
idx = 0
while idx < len(lines):
s = lines[idx].strip()
if not s:
idx += 1
continue
if s == "#": break
idx += 1
ca += 1
#res = "UNKNOWN" if s not in lan else lan[s] # 兩種寫法都可以
res = lan.get(s, "UNKNOWN")
result.append(f"Case {ca:d}: {res}\n")
sys.stdout.write("".join(result))
C++ 程式碼
使用時間約為 2 ms,記憶體約為 332 kB,通過測試。
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
unordered_map<string, string> lan =
{{"HELLO", "ENGLISH"},
{"HOLA", "SPANISH"},
{"HALLO", "GERMAN"},
{"BONJOUR", "FRENCH"},
{"CIAO", "ITALIAN"},
{"ZDRAVSTVUJTE", "RUSSIAN"}};
int ca = 0;
string s;
while(cin >> s && s != "#") {
ca++;
cout << "Case " << ca << ": ";
if (lan.find(s) == lan.end()) cout << "UNKNOWN\n";
else cout << lan[s] << "\n";
}
return 0;
}
沒有留言:
張貼留言