notes/OJ notes/pages/Leetcode First-Unique-Character-In-a-String.md

90 lines
1.3 KiB
Markdown
Raw Normal View History

2022-06-14 23:33:35 +08:00
# Leetcode First-Unique-Character-In-a-String
#### 2022-06-14 13:10
---
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Algorithms:
2022-09-03 15:41:36 +08:00
#algorithm
2022-06-14 23:33:35 +08:00
##### Data structures:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
#DS #string #array #hash_table
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Difficulty:
2022-09-03 15:41:36 +08:00
#leetcode #coding_problem #difficulty-easy
2022-06-14 23:33:35 +08:00
##### Related topics:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
##### Links:
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
- [Link to problem](https://leetcode.com/problems/first-unique-character-in-a-string/)
2022-09-03 15:41:36 +08:00
---
2022-06-14 23:33:35 +08:00
### Problem
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
Given a string `s`, _find the first non-repeating character in it and return its index_. If it does not exist, return `-1`.
#### Examples
**Example 1:**
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
```markdown
**Input:** s = "leetcode"
**Output:** 0
```
**Example 2:**
```markdown
**Input:** s = "loveleetcode"
**Output:** 2
```
**Example 3:**
```markdown
**Input:** s = "aabb"
**Output:** -1
```
#### Constraints
2022-09-03 15:41:36 +08:00
- `1 <= s.length <= 105`
- `s` consists of only lowercase English letters.
2022-06-14 23:33:35 +08:00
### Thoughts
Really, really simple hash map problem.
Shouldn't have taken so much time.
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
> [!summary]
> Don't overlook simple problems! #tip
### Solution
```cpp
class Solution {
public:
int firstUniqChar(string s) {
// O(1) hashmap
int umap[26] = {};
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
int sSize = s.size();
for (int i = 0; i < sSize; i++) {
umap[s[i] - 'a']++;
}
2022-09-03 15:41:36 +08:00
2022-06-14 23:33:35 +08:00
for (int i = 0; i < sSize; i++) {
if (umap[s[i] - 'a'] == 1) {
return i;
}
}
return -1;
}
};
2022-09-03 15:41:36 +08:00
```