Java 23ms, easy to read


  • 0
    C
    public int firstUniqChar(String s) {
        if (s == null) {
            return - 1;
        }
        
        int[] chars = new int[26];
        Arrays.fill(chars, -1);
        
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (chars[c - 'a'] == -1) {
                chars[c - 'a'] = i;
            } else {
                chars[c - 'a'] = -2;
            }
        }
        
        int min = -1;
        for (int i = 0; i < 26; i++) {
            if (chars[i] != -1 && chars[i] != -2) {
                if (min == -1 || min > chars[i]) {
                    min = chars[i];
                }
            }
        }
        return min;
    }

Log in to reply
 

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