Java - Remember Indexes

  • 0

    The idea is to remember the indexes of each character in the string, then return the min index. We only need indexes of unique characters; if a character is repeated, mark it so.

    The following code is a little messy; we use ~i to represent the index; 0 means the character is not in the string; 1 means the character is repeated in the string.

        int[] indexes = new int[26];
        for(int i=0; i<s.length(); i++)
            int ch = s.charAt(i)-'a';
            indexes[ch] = indexes[ch]==0 ? ~i : 1;
        int min = Integer.MAX_VALUE;
        for(int index : indexes)
            if(index<0) min=Math.min(min, ~index);
        return min==Integer.MAX_VALUE ? -1 : min;

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.