Java - What is the best way to find first duplicate character in a string

前端 未结 7 1367
我寻月下人不归
我寻月下人不归 2020-12-19 09:02

I have written below code for detecting first duplicate character in a string.

public static int detectDuplicate(String source) {
    boolean found = false;         


        
7条回答
  •  时光取名叫无心
    2020-12-19 09:47

    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.

提交回复
热议问题