Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b951e28

Browse files
feat: solve No.387
1 parent 01b5c56 commit b951e28

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /