|
| 1 | +# 387. First Unique Character in a String |
| 2 | + |
| 3 | +- Difficulty: Easy. |
| 4 | +- Related Topics: Hash Table, String, Queue, Counting. |
| 5 | +- Similar Questions: Sort Characters By Frequency, First Letter to Appear Twice. |
| 6 | + |
| 7 | +## Problem |
| 8 | + |
| 9 | +Given a string `s`, **find the first non-repeating character in it and return its index**. If it does not exist, return `-1`. |
| 10 | + |
| 11 | + |
| 12 | +Example 1: |
| 13 | +``` |
| 14 | +Input: s = "leetcode" |
| 15 | +Output: 0 |
| 16 | +```Example 2: |
| 17 | +``` |
| 18 | +Input: s = "loveleetcode" |
| 19 | +Output: 2 |
| 20 | +```Example 3: |
| 21 | +``` |
| 22 | +Input: s = "aabb" |
| 23 | +Output: -1 |
| 24 | +``` |
| 25 | + |
| 26 | +**Constraints:** |
| 27 | + |
| 28 | + |
| 29 | + |
| 30 | +- `1 <= s.length <= 105` |
| 31 | + |
| 32 | +- `s` consists of only lowercase English letters. |
| 33 | + |
| 34 | + |
| 35 | + |
| 36 | +## Solution |
| 37 | + |
| 38 | +```javascript |
| 39 | +/** |
| 40 | + * @param {string} s |
| 41 | + * @return {number} |
| 42 | + */ |
| 43 | +var firstUniqChar = function(s) { |
| 44 | + var map = {}; |
| 45 | + for (var i = 0; i < s.length; i++) { |
| 46 | + map[s[i]] = (map[s[i]] || 0) + 1; |
| 47 | + } |
| 48 | + for (var i = 0; i < s.length; i++) { |
| 49 | + if (map[s[i]] === 1) return i; |
| 50 | + } |
| 51 | + return -1; |
| 52 | +}; |
| 53 | +``` |
| 54 | + |
| 55 | +**Explain:** |
| 56 | + |
| 57 | +nope. |
| 58 | + |
| 59 | +**Complexity:** |
| 60 | + |
| 61 | +* Time complexity : O(n). |
| 62 | +* Space complexity : O(1). |
0 commit comments