本题与KY67子串计算类似,都是使用while+find循环匹配子串,这个匹配完了pos++匹配下一个范围的子串
pair在本题中的使用与map几乎没有太大区别,连迭代器遍历访问都一致,只是map自动按键升序排序在有些情况下反而不合适
// #include <iostream> // #include <string> // using namespace std; // int main() { // string str1, str2; // // 读取包含空格的字符串,因为 cin 在遇到空格时会停止读取 // // 循环读取整行输入,直到遇到'#'结束 // while (getline(cin, str1) && str1 != "#") { // getline(cin, str2); // 读取第二行字符串 // // 遍历str1中的每个字符,统计在str2的出现次数 // for (char c : str1) { // int count = 0; // // 遍历str2中的每个字符,统计c在str2中出现的次数 // for (char s : str2) { // if (s == c) { // count++; // } // } // // 输出结果,格式为:c n // cout << c << " " << count << endl; // } // } // return 0; // } #include <iostream> #include <string> #include <vector> #include <utility> // pair 的头文件 using namespace std; int main() { string str1, str2; // 用map默认会按键升序排序对于本题不合适,用vector和pair组合实现按字符顺序统计每一位字符出现的次数 while (getline(cin, str1) && getline(cin, str2)) { vector<pair<char, int>> count; if (str1 == "#") { break; } for (int i = 0; i < str1.size(); i++) { char cmp = str1[i]; int pos = 0; int cnt = 0; while ((pos = str2.find(cmp, pos)) != string::npos) { cnt++; pos++; } count.push_back(make_pair(cmp, cnt)); } // 输出结果 for (auto it = count.begin(); it != count.end(); it++) { cout << it->first << " " << it->second << endl; } } return 0; }