日期:2026年5月10日
ZeroJudge 題目連結:c929. 蝸牛老師的點名單-續
解題想法
這題如果用 Python 解題很快,只要先讀取分割用的字串,再將第二行字串用 split 代入第一行字串分割就好了。如果用 C++ 解題,則要用 getline 讀取整行字串,再依序檢查第二行字串的每個字元,找出分割用字串的索引值,再用 substr 取出子字串。
Python 程式碼
使用時間約為 21 ms,記憶體約為 8.2 MB,通過測試。
s = input()
for t in input().split(s):
print(t)
使用時間約為 19 ms,記憶體約為 8.2 MB,通過測試。
s = input() # 分割用的字串
t = input() # 要被分割的字串
n = len(s) # 字串長度
pre = 0 # 前一個分割點
idx = t.find(s) # 從 t 之中找 s 的索引值
while idx != -1: # -1 代表沒找到
print(t[pre:idx]) # 印出分割後的子字串
pre = idx + n # 更新 pre
idx = t.find(s, pre) # 從 s[pre:] 找 t
if pre > 0: print(t[pre:]) # 最後一段
else: print(t) # 沒有分割
C++ 程式碼
使用時間約為 3 ms,記憶體約為 3.4 MB,通過測試。
#include <iostream>
using namespace std;
int main() {
string s, t;
getline(cin, s);
getline(cin, t);
size_t m = s.size(); // 字串長度
size_t pre = 0, idx = t.find(s); // 前一個分割點,在 t 之中找 s
while(idx != string::npos) { // 如果有找到 s 就繼續執行
size_t d = idx - pre; // 分割子字串長度
cout << t.substr(pre, d) << "\n";
pre = idx + m; // 更新 pre
idx = t.find(s, pre); // 從 t[pre] 開始找 s
}
if (pre > 0) cout << t.substr(pre) << "\n"; // 最後一段
else cout << t << "\n"; // 沒有分割
return 0;
}
沒有留言:
張貼留言