16 ms, very simple solution O(N)


  • 0
    E

    public class Solution {

     public int firstUniqChar(String s) {
    
    // Idea is to store the  character count in an array of length 26 (a-z). 
    // Then see if there is a character whose count is equal to 1( which means it appears only once in the string). 
    // Loop the original char array to get the first unique element in the char array (or the input String)
    
    //Time complexity: Complexiy O(N)
    
    
    int arr[] = new int[26]; // length is 26 because character count from a to z is 26
    char[] charArr = s.toCharArray();
    
    for (int i=0; i<charArr.length;i++)
    {
        int charIndex = ((int)charArr[i] -97); // subtracting it from 97 because ascii code for 'a' is 97
        arr[charIndex] += 1; 
    }
    
    for (int i=0; i<charArr.length;i++)
    {
        int charIndex = ((int)charArr[i] -97); // subtracting it from 97 because ascii code for 'a' is 97
        if (arr[charIndex] == 1)
        {
            return i;
        }
    }
    return -1;    
    

    }
    }


Log in to reply
 

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