387. First Unique Character in a String

1. Description

Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.

2. Example

Example 1:
s = “leetcode”
return 0.
s = “loveleetcode”
return 2.

3. Note

  • You may assume the string contains only lowercase English letters.

4. Solutions

My Accepted Solution

n = i_str.size()
Time complexity: O(n)
Space complexity: O(n)

class Solution 
{
public:
    // int firstUniqChar(string s)
    int firstUniqChar(string &i_str) 
    {
        vector<int> letterTimes(26);
        for(int i = 0; i < i_str.size(); i++)
            letterTimes[i_str[i] - 'a']++;
        
        for(int i = 0; i < i_str.size(); i++)
        {
            if(letterTimes[i_str[i] - 'a'] == 1)
                return i;
        }
        
        return -1;
    }
};
comments powered by Disqus