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;
}
相关推荐
张祥64228890410 分钟前
误差理论与测量平差基础笔记六
笔记·算法·概率论
txinyu的博客13 分钟前
std::function
服务器·开发语言·c++
mjhcsp1 小时前
透彻背包DP:从DFS暴力搜索到动态规划的逐步推导
算法·深度优先·动态规划
学嵌入式的小杨同学1 小时前
【嵌入式 C 语言实战】交互式栈管理系统:从功能实现到用户交互全解析
c语言·开发语言·arm开发·数据结构·c++·算法·链表
txinyu的博客1 小时前
static_cast、const_cast、dynamic_cast、reinterpret_cast
linux·c++
多米Domi0111 小时前
0x3f 第40天 setnx的分布式锁和redission,写了一天项目书,光背了会儿八股,回溯(单词搜索)
数据结构·算法·leetcode
乐迪信息1 小时前
乐迪信息解决港口船型识别难题!AI算法盒子检测船舶类型
人工智能·算法·智能电视
“αβ”1 小时前
TCP相关实验
运维·服务器·网络·c++·网络协议·tcp/ip·udp
梭七y1 小时前
【力扣hot100题】(151)课程表
算法·leetcode·哈希算法
孞㐑¥2 小时前
算法—滑动窗口
开发语言·c++·经验分享·笔记·算法