Description: | 计算最大连续重复字符串个数,比如: 输入:123234,最大连续重复字符串为23,个数为2 输入:5555,最大连续重复字符串为555,个数为2 输入:aaabbb 最大连续重复字符串为aa,个数为2;和bb,个数为2 必须存在重复的字符串才算,只出现一次的不算。可能存在多个相同长度的不同字符串,比如aa和bb |
Knowledge Points: | 字符串 |
Source: | 固网igo |
Phase: | Advanced |
Time Limit: | 10Sec |
Memory Limit: | 128MByte |
Input: | 一行字符串 |
Output: | 重复子串 个数。以:隔离,每个一行 如果存在多个,按到子串第一次出现的先后顺序依次输出 |
Sample Input: | 123234234123 |
Sample Output: | 123:2 234:2 |
解题代码:
import java.util.*; /** * Created by c00415904 on 2018/6/11. */ public class TestMaxRepeatSubStrs { public static void main(String[] args){ Scanner in = new Scanner(System.in); while(in.hasNextLine()){ String str = in.nextLine(); max(str); } } public static void max(String str){ int[][] array = new int[str.length()][str.length()]; int max = Integer.MIN_VALUE; int maxIndex = 0; array[0][0] = 1; for (int i=1;i<str.length();i++){ if (str.charAt(i) == str.charAt(0)) { array[0][i] = 1; array[i][0] = 1; }else{ array[0][i] = 0; array[i][0] = 0; } } for(int i = 1;i < str.length();i++){ for(int j = 1; j <str.length();j++){ if (str.charAt(i) == str.charAt(j)){ array[i][j] = array[i-1][j-1] + 1; }else{ array[i][j] = 0; } } } List<Integer> result = new ArrayList<>(); List<Integer> resultIndex = new ArrayList<>(); //倒三角 for (int i = 0; i < array.length ; i++){ for (int j = i + 1;j < array.length; j++){ if(array[i][j] > max){ max = array[i][j]; maxIndex = i; result.clear(); resultIndex.clear(); result.add(max); resultIndex.add(maxIndex); }else if (array[i][j] == max ){ result.add(array[i][j]); resultIndex.add(i); } } } Set<String> set = new HashSet<>(); for (int i = 0; i< result.size();i++) { String subStr = str.substring(resultIndex.get(i) - result.get(i) + 1 ,resultIndex.get(i) + 1); if (set.contains(subStr)){ continue; }else{ set.add(subStr); } int count = 0; int index = 0; while(str.indexOf(subStr,index) != -1){ index = str.indexOf(subStr,index)+1; count++; } System.out.println(subStr+":"+count); } } }