比如输入 ttabcftrgabcd,输出结果为 abc, canffcancd,输出结果为 can。
下面是解题代码:
import java.util.HashMap;
import java.util.Map;
/**
* 输入一个字符串,如何求最长的重复出现的字符串?<br>
* 比如输入 ttabcftrgabcd,输出结果为 abc, canffcancd,输出结果为 can。
*
* @author Tang
*/
public class Test {
public static void main(String[] args) {
System.out.println("ttabcftrgabcd中最长的重复字符串:" + computeMaxRepeatString("ttabcftrgabcd"));
System.out.println("canffcancd中最长的重复字符串:" + computeMaxRepeatString("canffcancd"));
System.out.println();
System.out.println("A中最长的重复字符串:" + computeMaxRepeatString("A"));
System.out.println("AB中最长的重复字符串:" + computeMaxRepeatString("AB"));
System.out.println();
System.out.println("ABCDBCD中最长的重复字符串:" + computeMaxRepeatString("ABCDBCD"));
System.out.println("ABCDBCDCD中最长的重复字符串:" + computeMaxRepeatString("ABCDBCDCD"));
System.out.println();
System.out.println("ABCDABCDCD中最长的重复字符串:" + computeMaxRepeatString("ABCDABCDCD"));
System.out.println("ABCDABCDBCDCD中最长的重复字符串:" + computeMaxRepeatString("ABCDABCDBCDCD"));
}
/**
* 计算最长的重复字符串
*
* @param str
* @return
*/
public static String computeMaxRepeatString(String str) {
String maxNumberKey = null;
Integer maxNumberNumber = 0;
int len = str.length();
if (len < 1) {
throw new RuntimeException("string is empty");
}
if (len < 2) {
return str.charAt(0) + "";
}
for (int i = 2; i <= len; i++) {//i = 2意思是至少两个字符才开始算字符串
Object[] maxValue = computeMaxRepeatString(str, i);
String numberKey = (String) maxValue[0];
Integer numberNumber = (Integer) maxValue[1];
if (numberNumber >= maxNumberNumber || numberNumber >= 2) {
maxNumberKey = numberKey;
maxNumberNumber = numberNumber;
}
}
return maxNumberKey;
}
private static Object[] computeMaxRepeatString(String str, int count) {
Map<String, Integer> numberMap = new HashMap<>();
String maxNumberKey = null;
Integer maxNumberNumber = 0;
for (int i = 0; i <= str.length() - count; i++) {
String temp = str.substring(i, i + count);
Integer charNumber = numberMap.get(temp);
if (charNumber == null) {
charNumber = 1;
} else {
charNumber++;
}
numberMap.put(temp, charNumber);
if (maxNumberKey == null) {
maxNumberKey = temp;
maxNumberNumber = charNumber;
} else {
if (charNumber > maxNumberNumber) {
maxNumberKey = temp;
maxNumberNumber = charNumber;
}
}
}
return new Object[] { maxNumberKey, maxNumberNumber };
}
}
打印结果:
ttabcftrgabcd中最长的重复字符串:abc
canffcancd中最长的重复字符串:can
A中最长的重复字符串:A
AB中最长的重复字符串:AB
ABCDBCD中最长的重复字符串:BCD
ABCDBCDCD中最长的重复字符串:BCD
ABCDABCDCD中最长的重复字符串:ABCD
ABCDABCDBCDCD中最长的重复字符串:ABCD