In today’s Programming Praxis exercise, our goal is to find the longest substring consisting of only two characters in a string. Let’s get started, shall we?
First, we group identical characters together and then take all the tails so that each tail starts with two unique groups of characters. This is to eliminate the need for special logic for cases where a substring starts with two identical characters. For each tail, we discard everything starting from the third unique letter. Of the remaining groups, we look for the longest one, giving preference to ones on the right.
lstuc :: Eq a => [a] -> [a] lstuc xs = foldr (\x a -> if length x > length a then x else a)  [concat $ a:b:takeWhile (flip elem [head a, head b] . head) cs | (a:b:cs) <- tails $ group xs]
Some tests to see if everything is working properly:
main :: IO () main = do print $ lstuc "abcabcabcbcbc" == "bcbcbc" print $ lstuc "abababcabc" == "ababab" print $ lstuc "abcacacabc" == "cacaca" print $ lstuc "acacbdbd" == "bdbd" print $ lstuc "aaccbdb" == "aacc" print $ lstuc "" == ""