[JAVA] Use alphabet count array / T : O(N), S : O(1)


  • 0
    J
    class Solution {
        public int firstUniqChar(String s) {
            int[] alpha = new int[26];
            char[] chs = s.toCharArray();
            
            for(int i = 0; i < chs.length; i++){
                if(alpha[chs[i]-'a'] == 0){
                    alpha[chs[i]-'a']=i+1;
                }
                else{
                    alpha[chs[i]-'a']=-1;
                }
            }
            
            int min = Integer.MAX_VALUE;
            for(int i = 0; i < alpha.length; i++){
                if(alpha[i] != 0 && alpha[i] != -1 && min > alpha[i]){
                    min = alpha[i];
                }
            }
            
            return (min == Integer.MAX_VALUE) ? -1 : min-1;
        }
    }
    

Log in to reply
 

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