0

私は文字の配列を持っています:

a b c x y d e f x y a b c t r e a b c

サイズ 2 以降の繰り返しパターンを見つけるにはどうすればよいですか?

配列は最後からトラバースする必要があります。b cこの例では、パターン、a bx yおよびサイズ 3:a b cおよびのパターンを見つける必要がありますx y z。一致する文字のインデックスとともに。

これまでのところ、配列を逆方向にトラバースしてパターンを見つけようとしました。

for (int size = 2; size < aLT.size(); size++) {
    for (int i = aLT.size() - 1; i >= 0; i--) {
        // code here
    }
}
4

3 に答える 3

0
int n = 2; // in your case 2 and 3
Map<String, List<Integer>> matches = new HashMap<String, List<Integer>>();
String charsString = new String( chars );
String current = null;
String rest = null;
for( int i = chars.length - n; i >= 0; i-- ) {
    current = charsString.substring( i, i + n );
    rest = charsString.substring( 0, i );
    int index = rest.indexOf( current );
    if( index > -1 ) {
        if( matches.containsKey( current ) ) {
            continue;
        }
        List<Integer> indices = new ArrayList<Integer>();
        indices.add( i );
        while( index > -1 ) {
            indices.add( index );
            index = rest.indexOf( current, index + 1 );
        }
        matches.put( current, indices );
    }
}

// print the results
for( Entry<String, List<Integer>> match : matches.entrySet() ) {
    System.out.println( match.getKey() + " with indices: " + match.getValue() );
}

出力は次のとおりです。

ab with indices: [16, 0, 10]
bc with indices: [17, 1, 11]
xy with indices: [8, 3]
于 2013-09-21T19:27:52.937 に答える