Java O(2n) Solution, 15ms, 97%


  • 0
    A
    public int firstUniqChar(String s) {
        /*
         * - Keep an int[] of size 26 to act as a map of char -> count
         * - O(n) | Scan once, filling out this map
         * - O(n) | Scan again, grabbing first char whose value in the map is 1
         */
        final int[] charMap = new int[26];
        final char[] chars = s.toCharArray();
        for(char c : chars) {
            final int cKey = c-97;
            charMap[cKey]++;
        }
        final int len = chars.length;
        for(int i=0; i<len; i++) {
            final int cKey = chars[i]-97;
            if(charMap[cKey]==1) {
                return i;
            }
        }
        return -1;
    }
    

Log in to reply
 

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