日期:2025年3月5日
ZeroJudge 題目連結:f341. 5.閱讀順序(Reading)
解題想法
這題考字串操作,在 Python 用字串切片很好寫,在 C++ 最好是使用 string 函式庫的 substr 及 algorithm 函式庫的 reverse 會比較好寫。
Python 程式碼
使用時間約為 25 ms,記憶體約為 3.3 MB,通過測試。
def solve(s, x):
if s == x: return s # 特例,直接回傳 s
n, m = len(s), len(x) # s、x 的長度
c = s.find(x) # 翻轉軸於 s 的索引值
if c == 0: # x 在開頭
ri = s[m:] # 取 x 右側的子字串
return ri[::-1] + s[:m] # 將 ri 放在左側並反向,加上 x 左側的子字串
elif c+m == n: # x 在結尾
le = s[:c] # 取 x 左側的子字事
return s[c:] + le[::-1] # x 右側的子字串,加上 le 放在右側並反向
else: # x 在中間
le, ri = s[:c], s[c+m:] # 取 x 左、右兩側的子字串
return ri[::-1] + s[c:c+m] + le[::-1] # ri 放到左側並反向,le 放在右側並反向
s = input().strip() # 原來的字串
x = input().strip() # 翻轉軸
print(solve(s, x)) # 呼叫 solve 並印出答案
C++ 程式碼
使用時間約為 2 ms,記憶體約為 348 kB,通過測試。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string solve(string s, string x) {
if (s == x) return s; // 特例,直接回傳 s
size_t n = s.size(), m = x.size(); // s、x 的長度
size_t c = s.find(x); // 翻轉軸於 s 的索引值
if (c == 0) { // x 在開頭
string ri = s.substr(m); // 取 x 右側的子字串
reverse(ri.begin(), ri.end()); // 將 ri 反向
return ri + s.substr(0, m); // 回傳 ri 加上 x 左側的子字串
} else if (c+m == n) { // x 在結尾
string le = s.substr(0, c); // 取 x 左側的子字事
reverse(le.begin(), le.end()); // 將 le 反向
return s.substr(c) + le; // 回傳 x 右側的子字串加上 le
} else { // x 在中間
string le = s.substr(0, c), ri = s.substr(c+m); // 取 x 左、右兩側的子字串
reverse(le.begin(), le.end()); // 將 ri 反向
reverse(ri.begin(), ri.end()); // 將 le 反向
return ri + s.substr(c, m) + le; // 回傳 ri + 中間的子字串 + le
}
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
string s, x; cin >> s >> x; // 原來的字串、翻轉軸
cout << solve(s, x) << "\n"; // 呼叫 solve 並印出答案
return 0;
}
沒有留言:
張貼留言