2022-06-14 23:33:35 +08:00
|
|
|
# Leetcode First-Unique-Character-In-a-String
|
|
|
|
|
|
|
|
#### 2022-06-14 13:10
|
|
|
|
|
|
|
|
---
|
|
|
|
##### Algorithms:
|
|
|
|
#algorithm
|
|
|
|
##### Data structures:
|
|
|
|
#DS #string #array #hash_table
|
|
|
|
##### Difficulty:
|
|
|
|
#leetcode #coding_problem #difficulty-easy
|
|
|
|
##### Related topics:
|
|
|
|
```expander
|
|
|
|
tag:#string OR tag:#hash_table
|
|
|
|
```
|
|
|
|
|
|
|
|
- [[cpp_std_unordered_map]]
|
|
|
|
- [[Leetcode Ransom-Note]]
|
2022-07-10 08:29:59 +08:00
|
|
|
- [[Leetcode Two-Sum-IV-Input-Is-a-BST]]
|
|
|
|
- [[Leetcode Valid-Anagram]]
|
2022-06-14 23:33:35 +08:00
|
|
|
|
|
|
|
|
|
|
|
##### Links:
|
|
|
|
- [Link to problem](https://leetcode.com/problems/first-unique-character-in-a-string/)
|
|
|
|
___
|
|
|
|
### Problem
|
|
|
|
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:**
|
|
|
|
```markdown
|
|
|
|
**Input:** s = "leetcode"
|
|
|
|
**Output:** 0
|
|
|
|
```
|
|
|
|
|
|
|
|
**Example 2:**
|
|
|
|
|
|
|
|
```markdown
|
|
|
|
**Input:** s = "loveleetcode"
|
|
|
|
**Output:** 2
|
|
|
|
```
|
|
|
|
|
|
|
|
**Example 3:**
|
|
|
|
|
|
|
|
```markdown
|
|
|
|
**Input:** s = "aabb"
|
|
|
|
**Output:** -1
|
|
|
|
```
|
|
|
|
|
|
|
|
#### Constraints
|
|
|
|
- `1 <= s.length <= 105`
|
|
|
|
- `s` consists of only lowercase English letters.
|
|
|
|
|
|
|
|
### Thoughts
|
|
|
|
|
|
|
|
Really, really simple hash map problem.
|
|
|
|
Shouldn't have taken so much time.
|
|
|
|
> [!summary]
|
|
|
|
> Don't overlook simple problems! #tip
|
|
|
|
|
|
|
|
### Solution
|
|
|
|
|
|
|
|
```cpp
|
|
|
|
class Solution {
|
|
|
|
public:
|
|
|
|
int firstUniqChar(string s) {
|
|
|
|
// O(1) hashmap
|
|
|
|
int umap[26] = {};
|
|
|
|
|
|
|
|
int sSize = s.size();
|
|
|
|
for (int i = 0; i < sSize; i++) {
|
|
|
|
umap[s[i] - 'a']++;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (int i = 0; i < sSize; i++) {
|
|
|
|
if (umap[s[i] - 'a'] == 1) {
|
|
|
|
return i;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
```
|