题解:P14161 [ICPC 2022 Nanjing R] 完美回文

· · 题解

题目分析

有一个长度为 n 的字符串,定义完美回文为:对这个字符串进行任意次循环移位后,得到的新字符串都是回文串。

我们可以修改字符串中的任意字符,求将给定字符串变成完美回文的最少修改次数。

我们引入循环移位为旋转

关键信息ℹ️:

得出结论完美回文必须所有字符都相同

所以 最少修改次数 = 总长度 - 出现最多的字符次数

解释样例

2
abcb
xxx

推导一个abcb

推导第二个xxx

AC代码 AC记录

#include <iostream>
#include <string>
#include <array>
using namespace std;

int main() {
    //ios::sync_with_stdio(false);
    //cin.tie(nullptr);

    int T;
    cin >> T;
    while (T--) {
        string s;
        cin >> s;

        array<int, 26> count{}; //统计26个字母出现的次数
        int max_count = 0; // 记录最大出现次数

        for (char c : s) {
            int idx = c - 'a';
            count[idx]++;
            if (count[idx] > max_count) {
                max_count = count[idx];
            }
        }

        cout << s.length() - max_count << '\n';
    }

    return 0;
}

另一种map统计 AC记录

#include <iostream>
#include <string>
#include <map>
using namespace std;

int main() {
    //ios::sync_with_stdio(false);
    //cin.tie(nullptr);

    int T;
    cin >> T;
    while (T--) {
        string s;
        cin >> s;

        map<char, int> count;
        int max_count = 0;

        for (char c : s) {
            count[c]++;
            if (count[c] > max_count) {
                max_count = count[c];
            }
        }

        cout << s.length() - max_count << '\n';
    }

    return 0;
}