Java solution beats 96%


  • 1
    Y
    public int firstUniqChar(String s) {
            if(s.length() == 0 || s == null) return -1;
            char[] chars = s.toCharArray();
            int[] count = new int[26];
            for(int i=0; i<chars.length; i++){
                count[chars[i] - 'a'] ++;
            }
            int index = s.length();
            for(int i=0; i<26; i++){
                if(count[i] == 1){
                    int idx = s.indexOf('a' + i);
                    index = Math.min(idx, index);
                }
            }
            return index == s.length() ? -1 : index; //all the chars are not unique
        }
    

Log in to reply
 

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