题解 | 小红的双生串 【力大砖飞】
小红的双生串
https://www.nowcoder.com/practice/099d6681234d4e3e95c0e0ade31929da?tpId=37&tags=&title=&difficulty=2&judgeStatus=&rp=1&sourceUrl=%2Fexam%2Foj%2Fta%3FtpId%3D37&gioEnter=menu
// 小红定义一个字符串是双生串,当且仅当其前半部分所有字符相同,后半部分所有字符相同
// 现在,小红拿到了一个字符串s
// 她每次操作可以修改一个字符
// 小红希望你求出将其修改为双生串的最小修改次数
// 也就是说我们要把字符串拆成两半,分别统计每段最多的字符数
// 开始我们的暴力循环,跟我的遍历说去吧!
// 主打一个力大砖飞!!!!
#include <iostream>
#include <map>
using namespace std;
int main() {
// ================== 优化部分 =============
// 优化IO速度(解除与C标准库的同步) 其实我也不懂什么意思,拿过来用就行
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
// ================= 输入部分 =============
string s;
// ================= 输出部分 =============
while(getline(cin, s)){
int n = s.size();
int count1 = 0; // 用来统计前半段最多的字符数
int count2 = 0; // 用来统计后半段最多的字符数
// 使用substr拆分字符串
string half1 = s.substr(0, n/2); // 前半段
string half2 = s.substr(n/2, n); // 后半段
map<char ,int > map1; // 统计前半段最多字符出现的次数
map<char ,int > map2; // 统计前半段最多字符出现的次数
// 开始遍历,给每个出现的字符+1
for(char c : half1) map1[c]++;
for(char c : half2) map2[c]++;
// 找到最大次数
for(auto& c : half1) count1 = max(count1 , map1[c]);
for(auto& c : half2) count2 = max(count2 , map2[c]);
// 答案 = 总数 - 前半段最大次数 - 后半段最大次数
int ans = n - count1 - count2;
cout << ans << "\n";
}
return 0;
}


SHEIN希音公司福利 280人发布