#include<bits/stdc++.h> using namespace std;

int n,a[110]; string name[110], s[110];

int main() { cin >> n; for (int i = 1; i <= n; i++) cin >> name[i] >> s[i]; int ans = 0; for(int i = 1;i <= n;i++){ for(int j = 0;j < s[i].size() - 2;j++){ if(s[i][j] == 's' && s[i][j+1] == 'o' && s[i][j+2] == 's') a[i]++; }
if(a[i] > ans) ans = a[i]; } for (int i = 1;i <= n;i++) if(a[i] == ans) cout << name[i] << ' '; cout << endl; cout << ans; return 0; }

题意简述

给定 n 个字符串,统计其中每个字符串中 'SOS' 出现的次数,输出出现次数最多的个数以及出现次数最多的字符串的名字。

解题思路

使用两个数组分别存储字符串和字符串对应的名称。对于每个字符串,遍历其中的所有子串,判断是否为 'SOS',如果是则计数器加一。同时记录出现次数最多的次数,最后输出对应的字符串名称和出现次数。

时间复杂度

遍历每个字符串,并遍历每个字符串的子串,时间复杂度为 O(nk),其中 k 为字符串的长度。

C++ 统计字符串中

原文地址: https://www.cveoy.top/t/topic/nehx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录