I have written below code for detecting first duplicate character in a string.
public static int detectDuplicate(String source) {
boolean found = false;
I can substantially improve your algorithm. It should be done like this:
StringBuffer source ...
char charLast = source.charAt( source.len()-1 );
int xLastChar = source.len()-1;
source.setCharAt( xLastChar, source.charAt( xLastChar - 1 ) );
int i = 1;
while( true ){
if( source.charAt(i) == source.charAt(i-1) ) break;
i += 1;
}
source.setCharAt( xLastChar, charLast );
if( i == xLastChar && source.charAt( xLastChar-1 ) != charLast ) return -1;
return i;
For a large string this algorithm is probably twice as fast as yours.