2024-02-05 Daily Challenge
Today I have done leetcode's February LeetCoding Challenge with cpp
.
February LeetCoding Challenge 5
Description
First Unique Character in a String
Given a string s
, find the first non-repeating character in it and return its index. If it does not exist, return -1
.
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.
Solution
class Solution {
public:
int firstUniqChar(string s) {
vector<int> pos(26, INT_MAX - 1);
for(int i = 0; i < s.length(); ++i) {
if(pos[s[i] - 'a'] == INT_MAX - 1) {
pos[s[i] - 'a'] = i;
} else {
pos[s[i] - 'a'] = INT_MAX;
}
}
int result = *min_element(pos.begin(), pos.end());
return result > s.length() ? -1 : result;
}
};
// Accepted
// 105/105 cases passed (15 ms)
// Your runtime beats 97.21 % of cpp submissions
// Your memory usage beats 24.32 % of cpp submissions (11.9 MB)