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

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

    O(1) Algorithm

    Your solution is O(n^2) because of the two nested loops.

    The fastest algorithm to do this is O(1) (constant time):

    public static int detectDuplicate(String source) {
        boolean[] foundChars = new boolean[Character.MAX_VALUE+1];
        for(int i = 0; i < source.length(); i++) {
            if(i >= Character.MAX_VALUE) return Character.MAX_VALUE;
            char currentChar = source.charAt(i);
            if(foundChars[currentChar]) return i;
            foundChars[currentChar] = true;
        }
        return -1;
    }
    

    However, this is only fast in terms of big oh.

提交回复
热议问题