Java real O(n)+constant solution


  • 0
    B

    this is a simple idea! use 2 negative number to represent "duplicated" and "not scanned"
    -2 represent duplicated letter
    -1 represent not scanned

    public int firstUniq_mineChar(String s) {
            if(s.length()==0){
                return -1;
            }
            int[] alphabet = new int[26];
            Arrays.fill(alphabet, -1);
            for(int i=0;i<s.length();i++){
                char c = s.charAt(i);
                if(alphabet[c-'a'] == -1){
                   alphabet[c-'a'] = i;
                }else if(alphabet[c-'a'] == -2){
                   continue;
                }else{
                   alphabet[c-'a'] = -2;    
                }
            }
            int result = Integer.MAX_VALUE;
            for(int i : alphabet){
                if(i >= 0){
                    result = Math.min(result, i);
                }
            }
            return result!=Integer.MAX_VALUE?result:-1;
        }
    

Log in to reply
 

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