# 387. First Unique Character in a String

### Leetcode

<https://leetcode.com/problems/first-unique-character-in-a-string/>

### 題目

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

### 解答 <a href="#ti-jie" id="ti-jie"></a>

* **方法一**

利用 map 來存儲遍歷過的元素，如果未遍歷過的值就設成 index，遍歷過的設為 -1，最後抓出第一個不等於 -1 的 index。

注意：這裡利用 map 儲存元素是為了保證 order 次序是由前到後加入的，如果用 object 話沒辦法保證次序是對的。

```
var firstUniqChar = function(s) {
    const map = new Map();
    
    for(let i=0; i<s.length; i++) {
        const char = s[i];
        if(map.get(char) === undefined) {
          map.set(char, i);
        } else {
          map.set(char, -1);
        }
    }
    
    for (const value of map.values()) {
      if(value !== -1) return value;
    }
    return -1;
};
```

Runtime: 145 ms, faster than 39.62% of JavaScript online submissions for First Unique Character in a String.

Memory Usage: 42.1 MB, less than 65.41% of JavaScript online submissions for First Unique Character in a String.

### 測資

```
let s = "leetcode";
s = "loveleetcode";
s = "aabb";

console.log(firstUniqChar(s));
```
