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

前端 未结 7 1403
我寻月下人不归
我寻月下人不归 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条回答
  •  旧时难觅i
    2020-12-19 09:35

    This is O(n**2), not O(n). Consider the case abcdefghijklmnopqrstuvwxyzz. outerIndex will range from 0 to 25 before the procedure terminates, and each time it increments, innerIndex will have ranged from outerIndex to 26.

    To get to O(n), you need to make a single pass over the list, and to do O(1) work at each position. Since the job to do at each position is to check if the character has been seen before (and if so, where), that means you need an O(1) map implementation. A hashtable gives you that; so does an array, indexed by the character code.

    assylias shows how to do it with hashing, so here's how to do it with an array (just for laughs, really):

    public static int detectDuplicate(String source) {
        int[] firstOccurrence = new int[1 << Character.SIZE];
        Arrays.fill(firstOccurrence, -1);
        for (int i = 0; i < source.length(); i++) {
            char ch = source.charAt(i);
            if (firstOccurrence[ch] != -1) return firstOccurrence[ch];
            else firstOccurrence[ch] = i;
        }
        return -1;
    }
    

提交回复
热议问题