Java solution with comment: using array to mark each letter


  • 0
    H
        public int firstUniqChar(String s) {
            
            int[] letters = new int[26];
            int min = s.length()*2;
            
            for (int i = 0; i < s.length(); i++) {
                int c = s.charAt(i) - 'a';
                
                if (letters[c] == 0) {
                    letters[c] = i+1;   // plus 1 to avoid true 0
                } else {
                    letters[c] = min;    // duplicate, mark as len
                }
            }
            
            // for each element, 0 means no show, min*2 means repeat, otherwise it's the position + 1
            for (int i = 0; i < 26; i++) {
                
                if (letters[i] < min && letters[i] != 0)
                    min = letters[i];
            }
            
            // if min equal to original value, return -1; otherwise return the position (minus 1)
            return min == s.length()*2 ? -1 : min-1;
        }
    

Log in to reply
 

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