Комментарии:
An excellent idea to improve the performance of this code by someone:
For this question, you don't need to check for substrings of length 3+. The answer string has a length of at most 3. Suppose say there exists a string of length >=4 which satisfies the given conditions then definitely there exists another substring of length <4 which also satisfies the conditions. So the for loop in line 59 we could change the condition to len<4