Java solution that beats 88%


  • 0
    T
    public int firstUniqChar(String s) {
        if( s==null || s.length() == 0 ) return -1;
        
        int[] bucket = new int[26];
        int[] order = new int[26];
        int count = 0;
        int minOrder = s.length();
        
        char[] charArray = s.toCharArray();
        
        for( char c: charArray ){
            bucket[c-'a']++;
            if( order[c-'a'] == 0 ){
                order[c-'a'] = count;
            }
            count++;
        }
        for( int i=0; i<bucket.length; i++ ){
            if( bucket[i] == 1 ){
                if( order[i]<minOrder ){
                    minOrder = order[i];
                }
            }
        }
        
        return minOrder==s.length()? -1:minOrder ;
    }
    

    The idea is to fill a bucket with size 26 (since only lower case letters) and also keep track of the order (index) of the string. Then return the least index that appear once.


Log in to reply
 

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