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

前端 未结 7 1362
我寻月下人不归
我寻月下人不归 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:52

    Okay, I found below logic to reduce O(N^2) to O(N).

    public static int detectDuplicate(String source) {
        int index = -1;
        boolean found = false;
        final long start = System.currentTimeMillis();
    
        for(int i = 1; i <= source.length() && !found; i++) {
            if(source.charAt(i) == source.charAt(i-1)) {
                index = (i - 1);
                found = true;
            }
        }
    
        System.out.println("Time taken --> " + (System.currentTimeMillis() - start) + " ms. for string of length --> " + source.length());
        return index;
    }
    

    This also shows performance improvement over my previous algorithm which has 2 nested loops. This takes 130ms. to detect first duplicate character from 63million characters where the duplicate character is present at the end.

    I am not confident if this is the best solution. If anyone finds a better one, please please share it.

    Thanks,

    NN

    0 讨论(0)
提交回复
热议问题