Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Last active March 26, 2022 16:41
Show Gist options
  • Save dgodfrey206/70734d5d4bf3301a1512 to your computer and use it in GitHub Desktop.
Save dgodfrey206/70734d5d4bf3301a1512 to your computer and use it in GitHub Desktop.
HackerRank2
#include <iostream>
#include <string>
#include <cctype>
#include <cassert>
namespace detail {
bool isMatchingPair(char c1, char c2) {
return std::isupper(c1) && std::tolower(c1) == c2;
}
}
int findMatchingPair(const std::string& input) {
using detail::isMatchingPair;
if (!input.size() || !std::isupper(input[0])) {
return -1;
}
char lastUpper = input[0];
char const* lastLower = nullptr;
char prev = input[0];
int idx = -1;
for (int i = 1; i < input.size(); ++i) {
if (isMatchingPair(lastUpper, input[i])) {
lastLower = &input[i];
idx = i;
}
else if (std::isupper(input[i])) {
prev = input[i];
}
else if (lastLower && *lastLower == input[i]) {
return idx;
}
else if (isMatchingPair(prev, input[i])) {
lastLower = &input[i];
idx = i;
} else {
return idx;
}
}
return idx;
}
int main() {
assert(findMatchingPair("ABba") == 3);
assert(findMatchingPair("ABbCca") == 5);
assert(findMatchingPair("ABbba") == 2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment