Last active
December 7, 2022 08:54
-
-
Save BroVic/37b108ecad1b3ea898939c18947e2e7d to your computer and use it in GitHub Desktop.
CodeSignal #4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <iostream> | |
#include <map> | |
#include <utility> | |
using namespace std; | |
int solution(string s1, string s2) | |
{ | |
map<char, int> charLastposMap{}; | |
int matches{}; | |
for (auto ch : s1) | |
{ | |
// set the position in s2 from where we will start to look for a matching character | |
constexpr int novalue = -1; | |
auto pos = novalue; | |
auto it = charLastposMap.find(ch); | |
if (it != charLastposMap.end()) | |
pos = it->second; | |
// Look for the character in s2 | |
auto posfound = s2.find(ch, pos + 1); | |
if (posfound == s2.npos) | |
continue; | |
matches++; | |
// | |
if (pos == novalue) | |
charLastposMap.emplace(make_pair(ch, posfound)); | |
else | |
charLastposMap[ch] = posfound; | |
} | |
return matches; | |
} | |
int main() | |
{ | |
string one = {'a', 'a', 'c', 'c', 'a'}; | |
string two = {'a', 'd', 'c', 'b', 'a'}; | |
cout << "Matches: " << solution(one, two) << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment