字符串从1开始
for(int i = 2,j = 0; i <= n; i ++) {
while(j != 0 && s[i] != s[j+1] ) j = ne[j];
if(s[i] == s[j+1]) j++;
ne[i] = j;
}
例题:
141. 周期
import java.io.*;
import java.util.*;
public class Main {
static int N = 1000010;
static int []ne = new int [N];
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n,t=0;
while((n = sc.nextInt())!=0) {
char []s = (" "+ sc.next()).toCharArray();
for(int i = 2,j = 0; i <= n; i ++) {
while(j != 0 && s[i] != s[j+1] ) j = ne[j];
if(s[i] == s[j+1]) j++;
ne[i] = j;
}
System.out.println("Test case #" + ++t);
for(int i = 2; i <= n; i ++) {
int k = i -ne[i];
if(i % k == 0 && i / k > 1)
System.out.println(i +" " + i / k);
}
System.out.println();
}
sc.close();
}
}