Categories:

Tags:



Problem

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Constraints

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.

Solution

The problem First Unique Character in a String can be solved by counting the number of appearances for each letters and then finding the earliest non-repeating character.

Implementation

class Solution
{
  public:
    int firstUniqChar(string s)
    {
        int count[26];

        memset(count, 0, sizeof(int) * 26);
        for (char ch : s)
            count[ch - 'a'] += 1;

        for (int i = 0; i < s.length(); i++)
            if (count[s[i] - 'a'] == 1)
                return i;

        return -1;
    }
};