题目大意
给出若干行字符串,其中每个字符串可能由字母或者数字组成,现在我们需要输出所有的合法数字以及每行合法数字的个数,合法数字是指没有前导0且字符串中不含有字母。然后题目还给出一个条件是如果当前行的结尾字符串和下一行开头字符串都是合法数字,那么他们是被当做拼起来的字符串且归属于上一行。
解题思路
很多细节!首先大体的思路是得到一共有多少行,因为如果下一行只有一个字符串且和上一行能够拼接,因此先将正确的每一行得到,然后去判断每行有多少正确的数字,这里尤其注意当只有一个’0’时是正确的,不能当做前导0,因为这个卡了三个多小时。
#include <bits/stdc++.h>
using namespace std;
vector<string> ans;
vector<int> tot;
vector<int> level;
string s, in;
int line;
bool isNum(string num) {
if (s.size() == 1 && s[0] == '0') return true;
if (isalpha(num[0]) || isalpha(num.back()) || num[0] == '0')
return false;
for (int i = 1; i < num.size() - 1; i++)
if (isalpha(num[i])) return false;
return true;
}
int main() {
// ios_base::sync_with_stdio(false);
// cin.tie(nullptr), cout.tie(nullptr);
line = 0;
while (getline(cin, s) && s[0] != '#') {
if (!(isdigit(in.back()) && isdigit(s[0])))
in += " " + s;
else
in += s;
line++;
level.push_back(in.size() - 1);
}
in.push_back(' ');
tot.resize(line);
s.clear();
for (int i = 0; i < in.size(); i++) {
if (in[i] == ' ') {
if (s.empty()) continue;
if (isNum(s)) {
ans.push_back(s);
int l = i - s.size();
for (int j = 0; j < level.size(); j++) {
if (l <= level[j]) {
tot[j]++;
break;
}
}
}
s.clear();
continue;
}
s += in[i];
}
// cout << in << endl;
// for (int i : level) cout << i << endl;
if (!ans.empty()) {
bool first = true;
for (int i = 0; i < ans.size(); i++) {
if (first) {
cout << ans[i];
first = false;
} else
cout << " " + ans[i];
}
cout << endl;
}
for (int it : tot) cout << it << endl;
return 0;
}
/*
6a
2
228
a895a
6
6673
6 374
a7
0
7
#
*/