From e12d5fafdbc02b908b7051ebd13b0a2d1288074c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Mon, 5 Feb 2024 20:12:50 +0100 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB387.=20First=20Unique=20Char?= =?UTF-8?q?acter=20in=20a=20String=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/first-unique-character-in-a-string.cpp | 44 ++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 cpp/first-unique-character-in-a-string.cpp 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; +}