Simple java solution with char-indexed array.


  • 0
    C

    Using a char-indexed array to store occurrence of each character in string s, returns the first character having count 1 in count array after the counting.

    class Solution {
        public int firstUniqChar(String s) {
            int[] charCount = new int[256]; // Count occurence of each character
            
            for (int i = 0; i < s.length(); i++){
                charCount[s.charAt(i)]++;
            }
            
            for(int j = 0; j < s.length(); j++){
                if (charCount[s.charAt(j)] == 1) return j;
            }
            
            return -1;
        }
    }
    

Log in to reply
 

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