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
62 Upvotes

129 comments sorted by

View all comments

2

u/salonabolic Sep 11 '13

C

#include <stdio.h>
#include <string.h>

int main() {
	char s[100];
	printf("Enter a string: ");
	scanf("%s", s);
	int start = 0;
	int diff = 0;
	char result[100] = "";

	for (int i = 0; i < strlen(s); i++){
		if (s[i] != s[start]) diff++;
		if (diff > 1 && (i - start) > strlen(result)) {
			strncpy(result, s + start, i - start); // copy string to result
			start = i; // set start top current
			diff = 0;
		} else {
			strncpy(result, s + start, i - start);
		}
	}
	printf("%s\n", result);
	return 0;
}