题目出处:洛谷 P1321
题目描述
一个长度为 (l(3le lle 255)) 的字符串中被反复贴有 boy
和 girl
两单词,后贴上的可能覆盖已贴上的单词(没有被覆盖的用句点表示),最终每个单词至少有一个字符没有被覆盖。问贴有几个 boy 几个 girl?
输入格式
一行被被反复贴有boy和girl两单词的字符串。
输出格式
两行,两个整数。第一行为boy的个数,第二行为girl的个数。
样例输入
......boyogirlyy......girl.......
样例输出
4
2
问题分析
基础模拟题。可以通过找规律来求解:
假设给我们的字符串是 s 。因为题目告诉我们每一个 boy 和 girl 都不会完全被覆盖,所以我们只需要判断:
- 如果 (s[i] == 'b') 或者 (s[i+1] == 'o') 或者 (s[i+2] == 'y') ,则说明原来 (s[i]) 是 “boy” 的 “b”,于是男孩的数量加1;
- 如果 (s[i] == 'g') 或者 (s[i+1] == 'i') 或者 (s[i+2] == 'r') 或者 (s[i+3] == 'l') ,则说明原来 (s[i]) 是 “girl” 的 “g”,于是女孩的数量加1。
我们用 boy_num 和 girl_num 来分别表示男孩和女孩的数量。
实现代码如下:
#include <bits/stdc++.h>
using namespace std;
int boy_num, girl_num;
string s;
int main() {
cin >> s;
int n = s.length();
for (int i = 0; i < n; i ++) {
if (s[i] == 'b' || i+1 < n && s[i+1] == 'o' || i+2 < n && s[i+2] == 'y') boy_num ++;
if (s[i] == 'g' || i+1 < n && s[i+1] == 'i' || i+2 < n && s[i+2] == 'r' || i+3 < n && s[i+3] == 'l') girl_num ++;
}
cout << boy_num << "
" << girl_num << endl;
return 0;
}