1. Problem Description:
Title: a string with length of n (2 < = n < = 1 000 000), ask whether the prefix string with length of K (k > 1) is a periodic string, i.e. k = A...A; if so, output K in the order of K from small to large, i.e. the number of cycles;
Sample Input
3 aaa
12 aabaabaabaab
0
Sample Output
Test case #1
2 2
3 3
Test case #2
2 2
6 2
9 3
12 4
2. In fact, it is the use of next array in KMP algorithm, assuming that next[j] = k
Then if the periodic string has: J% (J - K) remainder of 0, then the string is considered to be periodic, and the number of repetitions: j / (j - k)
The code is as follows:
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class next Array example_Period string{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); List<String> list = new ArrayList<String>(); while (true) { int n = sc.nextInt(); if (n == 0) { break; } String s = sc.next(); list.add(s); } for(int j = 0; j<list.size();j++) { String s = list.get(j); int[] next = next(s); System.out.println("Test case #" + (j + 1)); boolean flag = false; for(int i = 2; i < next.length; i++) { int k = next[i]; int t = i - k; if (i%t==0&&i/t>1){ System.out.println(i + " " + i / t); } } System.out.println(); } } private static int[] next(String s) { if (s == null || s.length() == 0) return null; int[] next = new int[s.length()+1]; next[0] = -1; if (s.length() == 1) return next; next[1] = 0; int j = 1; int k = next[j]; while (j < s.length()) { if (k == -1 || s.charAt(j) == s.charAt(k)) { next[++j] = ++k; } else { k = next[k]; } } return next; } }