文字列の中で最も連続した文字列を取得しようとしています。たとえば :最長リピートシーケンスではなく最大リピートシーケンス
入力:
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;
}
}
私はこれが割り当てだとします。 **あなたはDPをソリューションに使用する必要がありますか?あなたはJava Collectionsを許可されていますか? –
うん! DPを使用する必要はありません。そして、はい、私はJavaコレクションを使用することができます –