LeetCode/cpp/first-unique-character-in-a-string.cpp

45 lines
1 KiB
C++
Raw Permalink Normal View History

#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;
}