# 387. First Unique Character in a String

**<font color=red>难度: Easy</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/first-unique-character-in-a-string/description/

> 内容描述

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

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

Python作弊法

用Python的Counter模块

可以参考 

<https://pymotw.com/2/collections/counter.html>


```python
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = collections.Counter(s)
        for i, c in enumerate(s):
            if d[c] == 1:
                return i
        return -1
```


> 思路 2
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

利用问题的特性，因为只有可能是小写字母，所以可以用一个长度为26的array, 先数一遍char的数量，然后enumerate从左往右又来

```python 
class Solution(object):
    def firstUniqChar(self, s):
        """
        :type s: str
        :rtype: int
        """
        cnt = [0 for i in range(26)]
        for c in s:
            cnt[ord(c) - ord('a')] += 1

        for idx, c in enumerate(s):
            if cnt[ord(c) - ord('a')] == 1:
                return idx
        return -1
```
