日期:2025年5月16日
ZeroJudge 題目連結:k926. P3. 錯字校正 (Correction)
解題想法
這題測資不大,按照題目的要求模擬替換字母的過程,最後再計算原來的字串與替換後的字串不同的字母數量即可。
Python 程式碼
使用時間約為 20 ms,記憶體約為 3.3 MB,通過測試。
import sys
for line in sys.stdin:
s = list(line.strip()) # 輸入的字串
t = list(input().strip()) # 正確的字串
n = int(input()) # 修正次數
for _ in range(n): # 讀取 n 行修正資料
x, y = list(input().split()) # x 替換成 y
for i in range(len(s)): # 依序由 s 讀取字元
if s[i] == x: s[i] = y # 如果 s[i] 是 x 則換成 y
diff = sum([a != b for a, b in zip(s, t)]) # 計算 s, t 之中對應位置不相同的字母數量
print(diff)
C++ 程式碼
使用時間約為 3 ms,記憶體約為 344 kB,通過測試。
#include <iostream>
#include <string>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
string s; // 輸入的字串
while(cin >> s) {
int m = (int)s.size(); // s 的長度
string t; cin >> t; // 正確的字串
int n; cin >> n; // 修正次數
for(int i=0; i<n; i++) { // 讀取 n 行修正資料
char x, y; cin >> x >> y; // x 替換成 y
for(int j=0; j<m; j++) { // 依序由 s 讀取字元
if (s[j] == x) s[j] = y; // 如果 s[j] 是 x 則換成 y
}
}
int diff = 0;
for(int i=0; i<m; i++) { // 計算 s, t 之中對應位置不相同的字母數量
if (s[i] != t[i]) diff++;
}
cout << diff << "\n";
}
return 0;
}
沒有留言:
張貼留言