Java solution, 30ms...Has anyone found a more efficient way?


  • 0

    Has anyone found a more efficient way?

    public class Solution {
        public int firstUniqChar(String s) {
            if(s==null) return -1;
            if(s.isEmpty())return -1;
            
            int OFFSET = (int)'a';
            int[] dup_array = new int[26];
            int num_unique = 26;
            
            for(int i=0;i<s.length();i++){
                int pos = ((int)s.charAt(i)) - OFFSET;
                if(dup_array[pos] == 1){
                    num_unique--;
                }
                dup_array[pos] = dup_array[pos] + 1;
            }
            if(num_unique == 0) return -1;
            
            for(int j=0;j<s.length();j++){
                int pos = ((int)s.charAt(j)) - OFFSET;
                if(dup_array[pos] == 1) return j;
            }
            return -1;
        }
    }
    

Log in to reply
 

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