最少添加字符数(kmp-next数组)
作者:互联网
给定一个字符串str,只能在str的后面添加字符,生成一个更长的字符串,更长的字符串需要
包含两个str,且两个str开始的位置不能一样。求最少添加多少个字符。
其实就是求终止字符的next数组
知道了最大共用-》最少添加
public class Main{ public static String answer(String str) { if (str == null || str.length() == 0) { return ""; } char[] chas = str.toCharArray(); if (chas.length == 1) { return str + str; } if (chas.length == 2) { return chas[0] == chas[1] ? (str + String.valueOf(chas[0])) : (str + str); } int endNext = endNextLength(chas); return str + str.substring(endNext); } public static int endNextLength(char[] chas) { int[] next = new int[chas.length + 1]; next[0] = -1; next[1] = 0; int pos = 2; int cn = 0; while (pos < next.length) { if (chas[pos - 1] == chas[cn]) { next[pos++] = ++cn; } else if (cn > 0) { cn = next[cn]; } else { next[pos++] = 0; } } return next[next.length - 1]; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); String test1 = sc.nextLine(); System.out.println(answer(test1).length()-test1.length()); } }
标签:字符,cn,int,next,chas,length,str,kmp 来源: https://www.cnblogs.com/iwyc/p/15552145.html