Java O(N) solution 17ms


  • 0
    J

    public class Solution {
    public int firstUniqChar(String s) {
    int i = 1;
    char[] charArray = s.toCharArray();
    int[] count = new int[26];
    for(char c : charArray){
    if(count[c-97] == 0)
    {count[c-97] = i;}
    else if(count[c-97] > 0)
    {count[c-97]-=i;}
    i++;
    }
    int result = i;
    for(int j = 0; j < 26; j++){
    if(count[j] > 0)
    {result = Math.min(result, count[j]-1);}
    }
    if(result == i)
    {return -1;}
    return result;
    }
    }


Log in to reply
 

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