HDU 3746 Cyclic Nacklace
- 题意:给一个字符串,要让这个字符串有至少两个循环周期,求最少需要添加多少个字符。
- 注意:如果是abcabcab,ans = 1. 因为开始的时候就理解错了题意,以为是整体只有两个周期qaq
- 思路:循环节的长度为cycL = len - Next[ len ]。
- 那么如果最长公共前后缀长度Next[ len ] != 0 && len % cycL == 0,那么说明输入的字符串是循环节个数>1的循环字符串,不需要添加。
- 否则,字符串末尾的已经有的循环节的一部分的长度为len % cycL,那么答案就是cycL - len % cycL
举个例子
abcabcab
next[0] = -1
next[1] = 0
next[2] = 0
next[3] = 0
next[4] = 1
next[5] = 2
next[6] = 3
next[7] = 4;//abcabca中,前缀abca和后缀abca相同,a是前后缀的公共部分但是不影响
next[8] = 5;//abcabcab中,前缀abcab和后缀abcab相同,ab是前后缀的公共部分但是不影响
很显然循环节为abc,cycL = 3 == 8 % next[ 8 ] = 3
此时字符串末的已经有的循环节的一部分为ab = 2 == 8 % clcL = 2
所以需要添加clcL - 2 = 1
Sample Input
3
aaa
abca
abcde
Sample Output
0
2
5
Sample Input
3
ffde
sdfe
fgfgdsfgdfg
Sample Output
4
4
7
JAVA源码实现
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int group = scanner.nextInt();
String[] input = new String[group];
for (int i = 0; i < group; i++) {
input[i] = scanner.next();
}
List<Integer> result = new ArrayList<>();
for (int i = 0; i < input.length; i++) {
String s = input[i];
doWith(s, result);
}
for (Integer integer : result) {
System.out.println(integer);
}
}
private static void doWith(String s, List<Integer> result) {
int minCycle = getMinCycle(s);
if (minCycle < 0) {
result.add(-minCycle);
} else if (minCycle < s.length()) {
result.add(0);
} else {
result.add(s.length());
}
}
private static int getMinCycle(String s) {
int length = s.length();
boolean find = true;
int result = length;
for (int j = 1; j < length; j++) {
// j能被length整除,j有可能是要找的
if (length % j == 0) {
for (int i = j; i < length; i++)
if (s.charAt(i) == s.charAt(i % j)) {
find = true; //继续循环
} else {
// j不是我们要找的
find = false;
break;
}
} else {
int times = length / j + 1;
for (int k = 1; k < times; k++) {
String basic = s.substring(0, j);
if (k == times - 1) {
if (!basic.startsWith(s.substring(k * j, length))) {
break;
} else {
return -(j - length % j);
}
} else if (!basic.equals(s.substring(k * j, (k + 1) * j))) {
break;
}
}
}
if (find) {
// 终于找到了
result = j;
break;
}
}
return result;
}
}