Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ sorting text

Tags:

c++

algorithm

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?

like image 337
Kehlin Swain Avatar asked Nov 28 '22 14:11

Kehlin Swain


2 Answers

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));
like image 199
Igor Tandetnik Avatar answered Dec 08 '22 15:12

Igor Tandetnik


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
like image 29
bames53 Avatar answered Dec 08 '22 15:12

bames53