r/dailyprogrammer • 1 2 • Jun 10 '13

[Easy] Longest Two-Character Sub-String

(Easy): Longest Two-Character Sub-String

This programming challenge is a classic interview question for software engineers: given a string, find the longest sub-string that contains, at most, two characters.

Author: /u/Regul

Formal Inputs & Outputs

Input Description

Through standard console input, you will be given a string to search, which only contains lower-case alphabet letters.

Output Description

Simply print the longest sub-string of the given string that contains, at most, two unique characters. If you find multiple sub-strings that match the description, print the last sub-string (furthest to the right).

Sample Inputs & Outputs

Sample Inputs

abbccc
abcabcabcabccc
qwertyytrewq

Sample Outputs

bbccc
bccc
tyyt
60 Upvotes

129 comments sorted by

View all comments

1

u/jagt Jun 14 '13

Oldschool c++ with recursion. O(n^2).

#include <iostream>
#include <string>
#include <cstring>
using namespace std;

string seek2char(const char *s)
{
	int ix = 1, end = strlen(s);
	if (end < 2) return string(s);

	char a = s[0], b = '\0';
	for (; ix < end; ++ix)
	{
		if (!b && s[ix] != a) {
			b = s[ix]; // met char b
			continue;
		} else if (s[ix] == a || s[ix] == b) {
			continue; // met old char
		} else {
			break; // met new char
		}
	}

	string cur_longest = string(s, s+ix), next_longest = seek2char(s+1);
	return cur_longest.size() > next_longest.size() ? cur_longest : next_longest;
}

int main()
{
	cout << seek2char("0") << endl;
	cout << seek2char("abbccc") << endl;
	cout << seek2char("abcabcabcabccc") << endl;
	cout << seek2char("qwertyytrewq") << endl;
	return 0;
}