I was asked the following interview question:
If there are two string inputs what method can be used to print the letters the string inputs have in common. For example if the user input:
working
soaked
output:
ok
What is the best algorithm to solve the problem?
string a = "working";
string b = "soaked";
set<char> setA(a.begin(), a.end());
set<char> setB(b.begin(), b.end());
vector<char> common;
set_intersection(setA.begin(), setA.end(), setB.begin(), setB.end(),
back_inserter(common));
copy(common.begin(), common.end(), ostream_iterator<char>(cout));
In fact, if no further processing is needed on the intersection, can send it straight to cout
:
set_intersection(setA.begin(), setA.end(), setB.begin(), setB.end(),
ostream_iterator<char>(cout));
Your description isn't unambiguous but the way I read it you want to know what letters are the same including position.
#include <string>
#include <iostream>
#include <algorithm>
int main() {
std::string const a = "working";
std::string const b = "soaked";
for (int i = 0; i < std::min(a.size(), b.size()); ++i) {
if (a[i] == b[i]) {
std::cout << a[i];
}
}
}
Produces:
ok
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With