求字符串最大的重复字串

1,定义一个后缀数组

2,对后缀数组排序

3,找出最大的重复字串:与其重复的最大字串,一定是相邻的。


private static int partition(String[] src, int low, int high) {
	if (src == null) {
		return -1;
	}

	String pivotValue = src[low];
	while (low < high) {
		while (low < high && src[high].compareTo(pivotValue) > 0)
			high--;
		src[low] = src[high];
		while (low < high && src[low].compareTo(pivotValue) < 0)
			low++;
		src[high] = src[low];
	}

	src[low] = pivotValue;
	return low;
}

public static void quickSort(String[] src, int low, int high) {
	if (src == null) {
		return;
	}

	if (low < high) {
		int mid = partition(src, low, high);
		quickSort(src, low, mid - 1);
		quickSort(src, mid + 1, high);
	}

}

public static String[] getSuffixChars(String src) {
	if (src == null) {
		return null;
	}
	String[] suffixStrings = new String[src.length()];
	for (int i = 0; i < src.length(); i++) {
		suffixStrings[i] = src.substring(i);
	}

	return suffixStrings;
}

private static int commonStringLength(String str1, String str2){
	if(str1==null || str2==null)
		return -1;
	int len1 = str1.length();
	int len2 = str2.length();
	int commonLength = 0;
	
	for(int i=0; i<len1 && i<len2 ; i++){
		if(str1.charAt(i) != str2.charAt(i)){
			break;
		}
		commonLength++;	
	}
	return commonLength;
}
public static String getMaxRepeatSubString(String src) {
	// 生成后缀数组
	String[] suffixStrings = getSuffixChars(src);
	// 排序后缀数组
	quickSort(suffixStrings, 0, suffixStrings.length - 1);
	// 与其重复最多的字串,一定是相邻的两个字串
	int maxLength = 0;
	int maxLoc = 0;
	int commonLength = 0;
	for(int i=1; i< suffixStrings.length; i++){
		commonLength = commonStringLength(suffixStrings[i-1], suffixStrings[i]);
		if(commonLength > maxLength) {
			maxLength = commonLength;
			maxLoc = i-1;
		}
	}

	return suffixStrings[maxLoc].substring(0, maxLength);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值