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;
}
相关推荐
曼巴UE523 分钟前
UE5.3 C++ TArray系列(一)
开发语言·c++·ue5
菜鸟一枚在这42 分钟前
深度解析建造者模式:复杂对象构建的优雅之道
java·开发语言·算法
gyeolhada1 小时前
2025蓝桥杯JAVA编程题练习Day5
java·数据结构·算法·蓝桥杯
阿巴~阿巴~1 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先
给bug两拳1 小时前
Day9 25/2/22 SAT
算法
CoderCodingNo2 小时前
【GESP】C++二级真题 luogu-b3924, [GESP202312 二级] 小杨的H字矩阵
java·c++·矩阵
_Itachi__2 小时前
LeetCode 热题 100 73. 矩阵置零
算法·leetcode·矩阵
夏末秋也凉2 小时前
力扣-贪心-376 摆动序列
算法·leetcode
刃神太酷啦3 小时前
堆和priority_queue
数据结构·c++·蓝桥杯c++组