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]