最大重复序列而不是最长重复序列

时间:2017-01-26 07:01:43

标签: java string dynamic-programming

我试图在字符串中获得最重复的字符序列。 例如:

输入:

s = "abccbaabccba"

输出:

 2

我使用动态编程来计算重复序列,但这会返回最长的重复字符序列。例如:

输入:

s = "abcabcabcabc"

输出:

2   
2(abcabc,abcabc) instead of 4(abc,abc,abc,abc)

以下是我填写DP表并提取重复序列的代码部分。任何人都可以建议我如何获得最重复的序列?

 //Run through the string and fill the DP table.
        char[] chars = s.toCharArray();
        for(int i = 1; i <= length; i++){
            for(int j = 1; j <= length; j++){
                if( chars[i-1] == chars[j-1] && Math.abs(i-j) > table[i-1][j-1]){
                    table[i][j] = table[i-1][j-1] + 1;
                    if(table[i][j] > max_length_sub){
                        max_length_sub = table[i][j];
                        array_index = Math.min(i, j);
                    }
                }else{
                    table[i][j] = 0;
                }
            }               
        }       
        //Check if there was a repeating sequence and return the number of times it occurred.
        if( max_length_sub > 0 ){
            String temp = s;
            String subSeq = "";
            for(int i = (array_index - max_length_sub); i< max_length_sub; i++){
                subSeq = subSeq + s.charAt(i);
            }
            System.out.println( subSeq );
            Pattern pattern = Pattern.compile(subSeq);
            Matcher  matcher = pattern.matcher(s);
            int count = 0;
            while (matcher.find())
                count++;

            // To find left overs - doesn't seem to matter 
            String[] splits = temp.split(subSeq);
            if (splits.length == 0){
                return count;
            }else{
                return 0;
            }
        }

1 个答案:

答案 0 :(得分:1)

简单和转储,要考虑的最小序列是一对字符(*):

  • 遍历整个字符串,获取每一对连续的字符,例如使用forsubstring来获取字符;
  • 计算字符串中该对的出现次数,使用countOccurrences()或正则表达式创建方法indexof(String, int);和
  • 存储最大的计数,在循环外使用一个变量maxCount,并使用if检查实际计数是否更大(或Math.max()

(*)if&#34; abc&#34;发生5次,而不是&#34; ab&#34; (和&#34; bc&#34;)也会发生至少5次 - 所以只需搜索&#34; ab&#34;和&#34; bc&#34;,不需要检查&#34; abc&#34;

编辑没有剩菜,请参阅评论,摘要:

  • 检查第一个字符是否在整个字符串上重复,如果不是

  • 检查2个初始字符是否全部重复,如果不是

  • 检查3 ...

至少需要2个计数器/循环:一个用于测试的字符数,第二个用于测试的位置。可以使用一些算法来提高性能:字符串的长度必须可以被没有余数的重复字符的数量整除。