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

74 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
---
##### Algorithms:
#algorithm
##### Data structures:
#DS #string #array #hash_table
##### Difficulty:
#leetcode #coding_problem #difficulty-easy
##### Related topics:
##### 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;
}
};
```