The code below is a solution to the problem shown in the bullet points. Is the way the -1 return case is handled faulty?
- An input string is guaranteed to be made up of only lower case English letters.
- Return -1 if there are no unique characters (characters that only appear once) in the string.
- Otherwise, return the index [from the input string] of the first unique character in the string.
int64_t FirstUniqueCharInString(const std::string& s)
{
std::array<bool, 26U> seen{};
std::array<std::string::size_type, 26U> pos{};
pos.fill(std::string::npos);
for (auto i = static_cast<std::size_t>(0); i < s.size(); ++i)
{
auto array_index_for_current_char = static_cast<std::size_t>(s[i] - 'a');
pos.at(array_index_for_current_char) = seen.at(array_index_for_current_char) ?
std::string::npos : i;
seen.at(array_index_for_current_char) = true;
}
// static casting result and std::string::npos to int64_t to match return type of function which
// is int64_t to allow for negative values (we have to be able to return -1 when there are no unique chars).
int64_t result = static_cast<int64_t>(*std::min_element(pos.begin(), pos.end()));
return result == static_cast<int64_t>(std::string::npos) ? -1 : result;
}
int64_t
is a signed integer type. So it allows for negative numbers. Compare that touint64_t
.result
(or, if you prefer, elements of the pos array) earlier in the solution since those elements were of size type.... to the "world" of signed, which is needed for the return type so that the -1 case can be returned when applicable (i.e. when there is no unique char).