Codeforces Round 937 (Div. 4)----->E. Nearly Shortest Repeating Substring

一,思路:

1.这题很容易想到枚举n的因数(时间复杂度n^(1/2)),然后根据这个长度枚举字符串,看是否满足最多只有一个不相同(时间复杂度 n)。总的时间复杂度是 ( n根号n )的级别。又n是1e5级别所以可以过。但是当n是1e6就不行了。

2.难点在于如何判断,一个字符串的不同字符数量,主要是 hshahaha这个不好判断。由这个样例启发,我们可以将字符串反转和不反转两种情况求最小不相同字符数量。(只要是相同的反转过来也是相同的)。hshahaha------>ahahahsh。

二,代码:

复制代码
#include <iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<set>
#include<stack>
#include<queue>
#include<map>
using namespace std;

const int N=200;

typedef  long long ll;
typedef pair<int,int> pii;

string str;
int n;

bool check(int x){

    int res=1e9;
//反转和不反转两个数量的最小值
    for(int k=0;k<2;k++) {

        int cnt1=0;

//用双指针来计算不相同的字符数量
        for (int i = 0, j = x; j < n; j++) {
            if (str[j] != str[i]) cnt1++;
            i = (i + 1) % x;
        }

        res=min(res,cnt1);
        reverse(str.begin(), str.end());
    }

    if(res>1) return false;
    else return true;

}

void Solved() {

    cin>>n;
    cin>>str;

    int res=1e9;
//枚举因数
    for(int i=1;i<=n/i;i++){
        if(n%i==0){
           if(check(i)) res=min(res,i);
           if(check(n/i)) res=min(res,n/i);
        }
    }

    cout<<res<<endl;
}

int main()
{
    int t;
    cin>>t;

    while(t--) {
        Solved();
    }
    return 0;
}
相关推荐
我家大宝最可爱3 分钟前
动态规划:入门思考篇
算法·动态规划·代理模式
肉夹馍不加青椒14 分钟前
第三十三天(信号量)
java·c语言·算法
卷卷卷土重来23 分钟前
C++单例模式
javascript·c++·单例模式
古译汉书1 小时前
嵌入式-SPI番外之按钮驱动程序的编写-Day15
c语言·stm32·单片机·嵌入式硬件·mcu·算法
yuyanjingtao1 小时前
CCF-GESP 等级考试 2025年6月认证C++二级真题解析
c++·青少年编程·gesp·csp-j/s
快去睡觉~1 小时前
力扣48:旋转矩阵
算法·leetcode·矩阵
long_run2 小时前
C++之auto 关键字
c++
卡洛斯(编程版3 小时前
(1) 哈希表全思路-20天刷完Leetcode Hot 100计划
python·算法·leetcode
疯狂的代M夫3 小时前
C++对象的内存布局
开发语言·c++
NAGNIP3 小时前
DeepSeekMoE 架构解析
算法