Leetcode 387. 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
.
s
?Assumption: The string will have a length ranging from 1 to (10^5), and it will contain only lowercase English letters.
The problem specifies to return the index of the first unique character.
#include <iostream>
#include <string>
#include <vector>
int firstUniqChar(std::string s) {
std::vector<int> count(26, 0);
// Count the frequency of each character in the string
for (char ch : s) {
count[ch - 'a']++;
}
// Find the first character with a frequency of 1
for (int i = 0; i < s.length(); ++i) {
if (count[s[i] - 'a'] == 1) {
return i;
}
}
return -1; // No unique character found
}
int main() {
std::string s = "leetcode";
int result = firstUniqChar(s);
std::cout << "Index of first unique character: " << result << std::endl;
return 0;
}
This approach ensures that we efficiently find the index of the first unique character in linear time using a simple array for constant time character frequency lookup.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?