对于字符串的处理还是很弱,而且感觉最近没啥手感了,加油吧。
这题一开始有一些细节不清楚该怎么处理,发现有的是可以通过测试用例看出来的
还是看的别人代码学习的,还是要沉淀。。。。
对了,学到了all_of函数,好方便。
#include <bits/stdc++.h>
using namespace std;
struct contents {
int type;
string text;
};
vector<contents> art;
bool is_blank(const string& str) {
return std::all_of(str.begin(),str.end(),[](char c) {return c == ' ';});
}
string stripe(string str) {
int l = 0; while (l < str.size() && str[l] == ' ') {l++;}
int r = (int)str.size() - 1;
while (r >= 0 && str[r] == ' ') {r--;}
return str.substr(l, r - l + 1);
}
int main() {
std::ios::sync_with_stdio(false);
int n;
cin >> n;
string tmp;
// pre process
while (getline(cin,tmp)) {
if (!is_blank(tmp)) break;
}
// if list of first line
if (tmp.size() >= 2 && tmp.substr(0,2) == "* ") {
art.push_back({1,stripe(tmp.substr(2))});
} else {
// not list
art.push_back({2, stripe(tmp)});
}
long long ans = 0;
bool las_line_blank = false;// last line is blank ?
while (getline(cin, tmp)) {
if (is_blank(tmp)) { // if empty just ignore
las_line_blank = true;
} else {
// a new line , just add into art
if (las_line_blank) {
las_line_blank = false;// new content
if (tmp.size() >= 2 && tmp.substr(0,2) == "* ") {
art.push_back({1,stripe(tmp.substr(2))});
} else {
art.push_back({2, stripe(tmp)});
}
} else {
//add by type
auto& cur = art.back();
//list type 1 presents first line of each component, 3 presents other lines
if (cur.type == 1 || cur.type == 3) {
// list other lines
if (tmp.size() >= 2 && tmp.substr(0,2) == " ") {
cur.text += " ";
cur.text += stripe(tmp.substr(2));
} else if (tmp.size() >= 2 && tmp.substr(0,2) == "* ") {
//list first line
art.push_back({3, stripe(tmp.substr(2))});
} else {
// phase
art.push_back({2,stripe(tmp)});
}
} else {
if (tmp.size() >= 2 && tmp.substr(0,2) == "* ") {
//list first line
art.push_back({1, stripe(tmp.substr(2))});
} else {
// phase
cur.text += " ";
cur.text += stripe(tmp);
}
}
}
}
}
for (int i = 0; i < art.size(); i++) {
auto& str = art[i].text;
if (art[i].type != 3 && i > 0) {
ans++;// empty line
}
if (art[i].type == 2) {
for (int j = 0; j < str.size(); j += n) {
while (j < str.size() && str[j] == ' ')
j++;
ans++;
}
} else {
if (str.empty()) {ans++;}
else {
for (int j = 0; j < str.size(); j += (n - 3)) {
while (j < str.size() && str[j] == ' ') j++;
ans++;
}
}
}
}
cout << ans << '\n';
}