Skip to content

Instantly share code, notes, and snippets.

@BroVic
Last active December 7, 2022 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BroVic/37b108ecad1b3ea898939c18947e2e7d to your computer and use it in GitHub Desktop.
Save BroVic/37b108ecad1b3ea898939c18947e2e7d to your computer and use it in GitHub Desktop.
CodeSignal #4
#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