关于最后的高度等于 n -next[n]的解释(不一定对,仅供参考,如有错误,请大佬纠正)。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @program: 算法题
* @author: 上杉
* @create: 2021-05-20 20:03
**/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String[] fl = bf.readLine().split(" ");
int M = Integer.parseInt(fl[0]);
int N = Integer.parseInt(fl[1]);
String[] strs = new String[M+1];
for (int i = 0; i < M; i++) {
strs[i] = bf.readLine();
}
//枚举横向循环节的最小长度
int width = 1;
for (; width <= N ; width++) {
boolean flag = true;
for (int j = 0; j < M; j++) {
for (int k = width; k < N; k++) {
if (strs[j].charAt(k) != strs[j].charAt(k%width)){
flag = false;
break;
}
}
if (!flag)break;
}
if (flag){
break;
}
}
//角标从0开始,是我的独特的next的写法,大家可以参考
int[] next = new int[M+1];
next[0] = -1;
next[1] = 0;
for (int i = 2; i <= M; i++) {
int k = i - 1;
while (k > 0 && !strs[i-1].substring(0,width).equals(strs[next[k]].substring(0,width))){
k = next[k];
}
next[i] = next[k] + 1;
}
int heigh = M - next[M];
System.out.println(heigh * width);
}
}