r/dailyprogrammer • u/nint22 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
qwertyytrewqSample Outputs
bbccc
bccc
tyyt
View all comments
Show parent comment
3
u/leonardo_m Jun 11 '13
Your solution looks efficient. But I'd like it to store the best i and k, and perform a substr only at the end, to perform only one string copy.
This is a D port of your C++ code, with some changes because this is supposed to work with all kinds of Unicode text. (I have tried it with various strings, but I am not fully sure of its correctness, because Unicode is easy to get wrong when handled at low level, and despite the help of std.array methods that handle Unicode, to create 'result' I have used raw pointers.)
In D I perform no copies of the string, just a slicing.
The counters are used because in Unicode text a pointer difference can't tell you the length of a string.
Each D string is 2 words long, so this wastes about 3 words in the stack frame, but this is not a problem. Most D standard library is designed to work on ranges, instead of single iterators. Designing a good Unicode iterator for this program is too much work.
This code also shows how quickly easy problem solutions become less easy if you want them to be both efficient, flexible and correct.