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
qwertyytrewq
Sample Outputs
bbccc
bccc
tyyt
View all comments
Show parent comment
1
u/Urist_Mc_George Jun 13 '13 edited Jun 13 '13
Your Solution would work as well. But the break does not go out of the if structure, it ends the whole for loop. It is an optimisation, because we don't need to iterate over the remaining chars, after we found the first not matching char. We can't find a longer substring here.
I hope my explanation helps.
Edit:
Your code would not work in all cases:
Take abbbcb for example. abbb is clear, now the c my code would breake, and stop iterating over the chars. Without the break you would not increase the counter at the c, but go on to the last char b. Now the counter would get incremented as well.