a517簡單單字長度篩選與遞增字元位置
CPE:Decoding the message (UVa 11220)
不足長度的字跳過,但不消耗下一個取字位置。
解題思路
每行把下一個要取的位置設為0起算的k=0。依序掃描單字,只有len(word)>k才取word[k]並讓k加1;長度不足則完全略過,k維持不變。因此輸出每增加一個字母,下一次才改取更後面的位置。
換行代表一個解碼單字完成,所以k必須每行重設。輸入的空行分隔訊息,不是待解碼的普通文字行;保留英文字母大小寫,單字間多個空白可以split處理。每組印Case #k:,組與組之間一空行,最後一組可直接到EOF。
Step-by-step animation
示意:First I give money to Teresa
步驟 1 / 3
取第一個字母
First[0]=F,之後I太短,仍等待第2個字母。
First→F
I跳過
give
money
to
Teresa
- k
- 1
- 結果
- F
#include <iostream>
#include <string>
#include <sstream>
#include <limits>
using namespace std;
int main() {
int T;
cin >> T;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int tc = 1; tc <= T; ++tc) {
if (tc > 1)
cout << '\n';
cout << "Case #" << tc << ":\n";
string line;
bool started = false;
while (getline(cin, line)) {
if (!line.empty() && line.back() == '\r')
line.pop_back();
if (line.empty()) {
if (started)
break;
else
continue;
}
started = true;
istringstream in(line);
string word, result;
while (in >> word)
if (word.size() > result.size())
result += word[result.size()];
cout << result << '\n';
}
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。