1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00
LeetCode/cpp/first-unique-character-in-a-string.cpp
2024-02-05 20:12:50 +01:00

44 lines
1 KiB
C++

#include <algorithm>
#include <array>
#include <cassert>
#include <string>
#include <utility>
class Solution {
public:
int firstUniqChar(const std::string &s) {
std::array<std::pair<int, int>, 26> counters;
counters.fill(std::make_pair(0, static_cast<int>(s.size())));
for (auto i = 0; i < static_cast<int>(s.size()); ++i) {
auto &[count, index] = counters[s[i] - 'a'];
++count;
index = std::min(index, i);
}
int min_index = static_cast<int>(s.size());
for (const auto &[count, index] : counters) {
if (count != 1) {
continue;
}
min_index = std::min(min_index, index);
}
if (min_index == static_cast<int>(s.size())) {
return -1;
}
return min_index;
}
};
int main() {
Solution s;
assert(s.firstUniqChar("leetcode") == 0);
assert(s.firstUniqChar("loveleetcode") == 2);
assert(s.firstUniqChar("aabb") == -1);
return 0;
}