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

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

    As mentioned by others, your algorithm is O(n^2). Here is an O(N) algorithm, because HashSet#add runs in constant time ( the hash function disperses the elements properly among the buckets) - Note that I originally size the hashset to the maximum size to avoid resizing/rehashing:

    public static int findDuplicate(String s) {
        char[] chars = s.toCharArray();
        Set uniqueChars = new HashSet (chars.length, 1);
        for (int i = 0; i < chars.length; i++) {
            if (!uniqueChars.add(chars[i])) return i;
        }
        return -1;
    }
    

    Note: this returns the index of the first duplicate (i.e. the index of the first character that is a duplicate of a previous character). To return the index of the first appearance of that character, you would need to store the indices in a Map (Map#put is also O(1) in this case):

    public static int findDuplicate(String s) {
        char[] chars = s.toCharArray();
        Map uniqueChars = new HashMap (chars.length, 1);
        for (int i = 0; i < chars.length; i++) {
            Integer previousIndex = uniqueChars.put(chars[i], i);
            if (previousIndex != null) {
                return previousIndex;
            }
        }
        return -1;
    }
    

提交回复
热议问题