日期:2025年2月22日
ZeroJudge 題目連結:e975. 3. 情書解密 (Love)
解題想法
Python 可以用 find 在字串中找特定的子字串,如果有找到會回傳子字串開頭字元的索引值,沒有找到會回傳 -1;如果用 index 在沒有找到時會跳出錯誤訊息,所以用 find 比較好。
Python 程式碼
使用時間約為 32 ms,記憶體約為 3.3 MB,通過測試。
def test(s):
for i in range(26): # 依序測試偏移量 0 ~ 25
t = "" # 移動後的字串
for c in s: # 依序由 s 讀取字元 c,將 c 的編號 +i 轉成字元存入 t
if 'A' <= c <= 'Z': t += chr((ord(c)-ord('A')+i)%26 + ord('A'))
elif 'a' <= c <= 'z': t += chr((ord(c)-ord('a')+i)%26 + ord('a'))
j = t.find("love") # 在字串 t 中找 love,回傳索引值 j
k = t.find("Love") # 在字串 t 中找 Love,回傳索引值 k
if j != -1 or k != -1: return i # 如果 j 或 k 不等 -1,有找到 love 或 Love,回傳 i
return -1 # 如果跑完以上的 for loop 都沒有回傳值,則回傳 -1 代表沒有找到 love
line = input().strip() # 讀取一行字串,刪除最後面的 \n
ans = test(line) # 呼叫 test
if ans >= 0: print(ans)
else: print("-1")
C++ 程式碼
使用時間約為 2 ms,記憶體約為 348 kB,通過測試。
#include <iostream>
#include <string>
using namespace std;
int test(string s) {
for(int i=0; i<26; i++) { // 依序測試偏移量 0 ~ 25
string t = ""; // 移動後的字串
for(char c : s) { // 依序由 s 讀取字元 c,將 c 的編號 +i 轉成字元存入 t
if (c >= 'A' && c <= 'Z') t += char((c-'A'+i)%26 + 'A');
else if (c >= 'a' && c <= 'z') t += char((c-'a'+i)%26 + 'a');
}
int j = t.find("love"); // 在字串 t 中找 love,回傳索引值 j
int k = t.find("Love"); // 在字串 t 中找 Love,回傳索引值 k
if (j != -1 || k != -1) return i; // 如果 j 或 k 不等 -1,有找到 love 或 Love,回傳 i
}
return -1; // 如果跑完以上的 for loop 都沒有回傳值,則回傳 -1 代表沒有找到 love
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
string line; getline(cin, line); // 讀取一行字串
int ans = test(line); // 呼叫 test
cout << (ans >= 0 ? ans : -1) << "\n";
return 0;
}
沒有留言:
張貼留言