日期:2026年10月15日
ZeroJudge 題目連結:h192.黏包、分包
解題想法
基礎題庫裡面新出現的字串處理題。每組測資是多行輸入,要先將所有的測資接成一個很長的字串 $s$。假設 $s$ 長度為 $n$,用一個 while 迴圈從 $i = 0$ 開始依序讀取字元,分成以下 2 種狀況:
- 如果 $s[i]$ 不是 :,代表目前讀到的是代表長度的數字,將 $s[i]$ 暫存到字串 $u$。
- 如果 $s[i]$ 是 :,將 $u$ 轉成整數 $d$,結算長度為 $d$ 的子字串,可以用 Python 的字串切片或是 C++ 的 substr,從 $s[i+1]$ 開始取子字串,組合成題目規定的輸出格式,輸出完畢後重置字串 $u$ 並將 $i += d$。
Python 程式碼
解題時間約為 12 ms,使用記憶體約為 9.6 B。
def solve():
import sys
result = []
# 讀取多行測資,全部接成一行
s = "".join(sys.stdin.read().split())
# 依序讀取字元暫存至字串 u,讀到 : 輸出長度 u 的子字串
i, n = 0, len(s)
u = ""
while i < n:
if s[i] == ':':
d = int(u)
result.append(f"{u}:{s[i+1 : i+d+1]}\n")
i += d
u = ""
else:
u += s[i]
i += 1
sys.stdout.write("".join(result))
if __name__ == "__main__":
solve()
解題時間約為 13 ms,使用記憶體約為 9.6 B。
# 讀取多行測資,全部接成一行
s = ""
while True:
try:
t = input()
s += t
except EOFError:
break
# 依序讀取字元暫存至字串 u,讀到 : 輸出長度 u 的子字串
i, n = 0, len(s)
u = ""
while i < n:
if s[i] == ':':
d = int(u)
print(f"{u}:{s[i+1 : i+d+1]}")
i += d
u = ""
else:
u += s[i]
i += 1
C++ 程式碼
解題時間約為 1 ms,使用記憶體約為 3.5 MB。
#include <iostream>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
// 讀取多行測資,全部接成一行
string s, t;
while(cin >> t) s += t;
// 依序讀取字元暫存至字串 u,讀到 : 輸出長度 u 的子字串
int i = 0, n = (int)s.size();
string u;
while(i < n) {
if (s[i] == ':') {
int d = stoi(u);
cout << u << ":" << s.substr(i+1, d) << "\n";
i += d;
u.clear();
} else {
u += s[i];
}
i++;
}
return 0;
}
沒有留言:
張貼留言