#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int count_char_occurrences(const string &str, char target)
{
int count = 0;
for (char ch : str)
{
if (ch == target)
{
count++;
}
}
return count;
}
int min_changes(const string &s, char target)
{
int len = s.length();
if (len == 1)
{
// 单个字符的情况可以直接判断
return (s[0] == target) ? 0 : 1;
}
// 将字符串分成两半
int half = len / 2;
string left = s.substr(0, half);
string right = s.substr(half);
// 递归计算左右两部分变成下一个字符所需的最小修改次数
int left_min_changes = min_changes(left, target + 1);
int right_min_changes = min_changes(right, target + 1);
// 计算左右两部分中目标字符的个数
int left_count = half - count_char_occurrences(left, target);
int right_count = half - count_char_occurrences(right, target);
// 返回左右两部分最小修改次数的和
return min(left_min_changes + right_count, right_min_changes + left_count);
}
int main()
{
int t;
cin >> t;
while (t--)
{
int n;
string s;
cin >> n >> s;
cout << min_changes(s, 'a') << endl;
}
return 0;
}
xmuoj密码破译
最新推荐文章于 2024-08-18 18:02:49 发布