日期:2025年12月15日
ZeroJudge 題目連結:a011. 00494 - Kindergarten Counting Game
解題想法
這題要讀取整行字串之後依序讀取每個字元,用變數 last 記錄目前連續出現的字母數量,如果這個字元是字母則 last 加 1; 反之,前一個單字結束了,如果 last 大於 0,單字數量 cnt 加 1,再將 last 歸零。檢查完整行字串之後,記得要再結算一次,才不會漏掉最後一個單字。
Python 程式碼
使用時間約為 17 ms,記憶體約為 2.8 MB,通過測試。
import sys
for line in sys.stdin:
last, cnt = 0, 0
for c in line.strip():
if c.isalpha(): last += 1
else:
if last > 0: cnt += 1
last = 0
if last > 0: cnt += 1
print(cnt)
C++ 程式碼
使用時間約為 1 ms,記憶體約為 320 kB,通過測試。
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
ios::sync_with_stdio(0); cin.tie(0);
string s;
while(getline(cin, s)) {
int last = 0, cnt = 0;
for(char c : s) {
if (isalpha(c)) {
last++;
} else {
if (last > 0) cnt++;
last = 0;
}
}
if (last > 0) cnt++;
cout << cnt << "\n";
}
return 0;
}
沒有留言:
張貼留言