Java练习题-输入一个字符串,如何求最大重复出现的字符串()
比如输入 ttabcftrgabcd,输出结果为 abc, canffcancd,输出结果为 can。
下面是解题代码:
import java.util.HashMap;
import java.util.Map;
/** * 输入一个字符串,如何求最长的重复出现的字符串?
* 比如输入 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 = https://www.it610.com/article/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 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
【Java练习题-输入一个字符串,如何求最大重复出现的字符串()】转载于:https://my.oschina.net/tangzhichao/blog/781467
推荐阅读
- JAVA(抽象类与接口的区别&重载与重写&内存泄漏)
- 【生信技能树】R语言练习题|【生信技能树】R语言练习题 - 中级
- 事件代理
- Java|Java OpenCV图像处理之SIFT角点检测详解
- Node.js中readline模块实现终端输入
- java中如何实现重建二叉树
- 数组常用方法一
- 【Hadoop踩雷】Mac下安装Hadoop3以及Java版本问题
- Java|Java基础——数组
- RxJava|RxJava 在Android项目中的使用(一)