Easy and Concise Java


  • 1

    The beauty is we just need to scan the String s one time, and then for the 2nd pass we just iterate array of length 26. So this approach is good for input string with long length.

    public class Solution {
        public int firstUniqChar(String s) {
            if (s == null || s.length() == 0) return -1;
            int[] count = new int[26];
            Arrays.fill(count, -1);
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                if (count[c - 'a'] >= 0) count[c - 'a'] = -2;
                else if (count[c - 'a'] == -1) count[c - 'a'] = i;
            }
            int min = s.length();
            for (int i = 0; i < 26; i++) {
                if (count[i] >= 0) min = Math.min(min, count[i]);
            }
            return min == s.length() ? -1 : min;
        }
    }
    

Log in to reply
 

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