洛谷 P1308 统计单词数
思路
一开始,我的想法是不一次性读取第二行整行的字符串,二是一个单词一个单词地输出,再与第一行的字符串作比拟,然而提交代码之后发现了问题:如果第二行字符串的结尾是空格,就会出错。
错误代码
/* * @Description: * @Author: 多多 * @Date: 2020-10-25 17:35:26 * @LastEditTime: 2020-10-26 07:33:38 * @LastEditors: 多多 */#include <bits/stdc++.h>using namespace std;int main(){ freopen("./INPUT/P1308.in", "r", stdin); ios::sync_with_stdio(false); cin.tie(0); string s1, s2; cin >> s1; transform(s1.begin(), s1.end(), s1.begin(), ::tolower); bool bo = true; int pos = -1; int len_sum = 0; int sum = 0; while (cin >> s2) { transform(s2.begin(), s2.end(), s2.begin(), ::tolower); if (s1 == s2) { if (bo) { pos = len_sum; bo = false; } sum++; } len_sum += s2.length() + 1; } if (bo) { cout << -1 << endl; } else { cout << sum << " " << pos << endl; } return 0;}
接下来的思路
还是中规中矩一次性读入第二行字符串,再做子串匹配。
代码
/* * @Description: * @Author: 多多 * @Date: 2020-10-25 17:35:26 * @LastEditTime: 2020-10-26 08:55:34 * @LastEditors: 多多 */#include <bits/stdc++.h>using namespace std;int main(){ freopen("./INPUT/P1308.in", "r", stdin); ios::sync_with_stdio(false); cin.tie(0); string s1, s2; cin >> s1; transform(s1.begin(), s1.end(), s1.begin(), ::tolower); bool bo = true; int len_s1 = s1.length(); int pos = 0; int pos_first = -1; int len_sum = 0; int sum = 0; getline(cin, s2); getline(cin, s2); transform(s2.begin(), s2.end(), s2.begin(), ::tolower); while (s2.find(s1, pos) != string::npos) { pos = s2.find(s1, pos); if ((s2[pos - 1] == ' ' && s2[pos + len_s1] == ' ') || pos == 0) { if (bo) { pos_first = pos; bo = false; } sum++; } pos++; } if (bo) { cout << -1 << endl; } else { cout << sum << " " << pos_first << endl; } return 0;}