1.5 KiB
1.5 KiB
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:
tag:#string OR tag:#hash_table
- cpp_std_unordered_map
- Leetcode Ransom-Note
- Leetcode Two-Sum-IV-Input-Is-a-BST
- Leetcode Valid-Anagram
Links:
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:
**Input:** s = "leetcode"
**Output:** 0
Example 2:
**Input:** s = "loveleetcode"
**Output:** 2
Example 3:
**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
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;
}
};