In this Leetcode First Unique Character in a String problem solution, you have given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Leetcode First Unique Character in a String problem solution


Problem solution in Python.

class Solution:

def firstUniqChar(self, s: str) -> int:
    n=len(s)
    char=[0]*256
    
    for i in s:
        char[ord(i)]+=1
    idx=-1
    k=0
    
    for i in s:
        if char[ord(i)]==1:
            idx=k
            break
        k+=1
    return idx



Problem solution in Java.

class Solution {
    public int firstUniqChar(String s) {
        Map<Character, Integer> occurrences = new HashMap<>();
        for (char c : s.toCharArray()) {
            Integer count = occurrences.get(c);
            if (count == null) {
                occurrences.put(c, 1);
            } else {
                occurrences.put(c, ++count);
            }
        }
        for (int i = 0; i< s.length(); i++) {
            if (occurrences.get(s.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }
}


Problem solution in C++.

vector<int> debut(26, -1);
    for(int i = 0; i < s.size(); i++) {
      if(debut[s[i] - 'a'] >= 0) {
        debut[s[i] - 'a'] = -2;
      }
      else if(debut[s[i] - 'a'] == -1) {
        debut[s[i] - 'a'] = i;
      }
    }
    int res = INT_MAX;
    for(int i = 0; i < 26; i++) {
      if(debut[i] >= 0) {
        res = min(res, debut[i]);
      }
    }
    return res == INT_MAX ? -1 : res;


Problem solution in C.

int firstUniqChar(char * s){
    int l=strlen(s);
    int a[26];
    for(int j=0; j<26; j++)
        a[j]=0;
    for(int j=0; j<l; j++){
        a[*(s+j)-97]++;
        
    }
    for(int j=0; j<l; j++){
        if(  a[*(s+j)-97]==1)
            return j;
    }
    return -1;
}