cpp: add «387. First Unique Character in a String»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-02-05 20:12:50 +01:00
parent 0ad2295875
commit e12d5fafdb
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,44 @@
#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;
}