Skip to content

Instantly share code, notes, and snippets.

@juanfal
Created January 14, 2022 19:13
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 juanfal/3e26f218bcce4088a7c5804e7a762e4b to your computer and use it in GitHub Desktop.
Save juanfal/3e26f218bcce4088a7c5804e7a762e4b to your computer and use it in GitHub Desktop.
string difference
// t10e16.stringdiff.cpp
// juanfc 2022-01-14
//
#include <iostream>
#include <array>
using namespace std;
string diff(string a, string b);
int main()
{
cout << diff("telephone", "phonograph") << endl;
cout << diff("holograph", "dog") << endl;
return 0;
}
typedef array<int,256> TCharFreq;
TCharFreq getFreqs(string s);
string diff(string a, string b)
{
string res;
TCharFreq freqs_b = getFreqs(b);
for ( int i = 0; i < a.size(); ++i )
if (freqs_b[a[i]])
--freqs_b[a[i]];
else
res += a[i];
return res;
}
int count(string s, char c);
TCharFreq getFreqs(string s)
{
TCharFreq r;
for (int i = 0; i < 256; ++i) {
r[i] = count(s, i);
}
return r;
}
int count(string s, char c)
{
int cnt = 0;
for (int i = 0; i < s.size(); ++i) {
if (s[i] == c) {
++cnt;
}
}
return cnt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment