diff --git a/cpp/first-unique-character-in-a-string.cpp b/cpp/first-unique-character-in-a-string.cpp new file mode 100644 index 0000000..c9fb421 --- /dev/null +++ b/cpp/first-unique-character-in-a-string.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include +#include + +class Solution { + public: + int firstUniqChar(const std::string &s) { + std::array, 26> counters; + counters.fill(std::make_pair(0, static_cast(s.size()))); + + for (auto i = 0; i < static_cast(s.size()); ++i) { + auto &[count, index] = counters[s[i] - 'a']; + + ++count; + index = std::min(index, i); + } + + int min_index = static_cast(s.size()); + for (const auto &[count, index] : counters) { + if (count != 1) { + continue; + } + + min_index = std::min(min_index, index); + } + + if (min_index == static_cast(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; +}