cpp: add «387. First Unique Character in a String»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
0ad2295875
commit
e12d5fafdb
1 changed files with 44 additions and 0 deletions
44
cpp/first-unique-character-in-a-string.cpp
Normal file
44
cpp/first-unique-character-in-a-string.cpp
Normal 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;
|
||||
}
|
Loading…
Reference in a new issue