2 solutions

  • 0
    @ 2022-8-7 14:51:01

    《最大长度表》是关键

    #include<bits/stdc++.h>
    using namespace std;
    
    typedef long long ll;
    const int N = 1e6+5;
    
    #define lowbit(x) ((-x)&x)
    
    string p,s;
    bool flage;
    
    int Next[N];
    
    int main()
    {
    	int n;
    	cin>>n;
    	cin>>s;
    	int m = s.size();
    	s.insert(s.begin(),' ');//因为string是从0开始的,所以在开头加一个空格
    	for(int i=2,j=0;i<=m;i++)
    	{
    		while(j&&s[i]!=s[j+1]) j=Next[j];
    		if(s[i]==s[j+1]) j++;
    		Next[i]=j;
    	}
    	cout<<m-Next[m]<<endl;
    	return 0;
    }
    
    • 0
      @ 2022-8-6 11:49:28

      关键在于利用kmp的最大长度表,求出最长的重复子串,然后就可以求出最短不重复子串

      #include<iostream>
      	#include<cstring>
      	#define ll long long
      	using namespace std;
      	const int N = 1e6+7;
      	int l;
      	string n;
      	ll ne[N];
      	int main()
      	{
      		cin>>l;
      		cin>>n;
      		for(ll i = 1,j = 0; i < l;i++){
      			while(j > 0&& n[i] != n[j])j = ne[j - 1];
      			if(n[i] == n[j])j++;
      			ne[i] = j;
      		}
               cout<<l-ne[l - 1];
      	    return 0;
      	}
      
      • 1

      Information

      ID
      275
      Time
      1000ms
      Memory
      256MiB
      Difficulty
      7
      Tags
      # Submissions
      26
      Accepted
      8
      Uploaded By