## Posts Tagged ‘substring’

### Programming Praxis – Longest Substring Of Two Unique Characters

June 11, 2013

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?

`import Data.List`

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 ""              == ""```

### Programming Praxis – Longest Duplicated Substring

December 14, 2010

In today’s Programming Praxis exercise, our task is to implement the algorithm to find the longest duplicated substring in a word. Let’s get started, shall we?

Some imports:

```import Data.List
import qualified Data.List.Key as K
```

It seems we have yet another case of simply translating the English description to Haskell syntax: create a list of suffixes, sort, get the longest common prefix of all adjacent pairs and return the longest one.

```lds :: Ord a => [a] -> [a]
lds = K.maximum length . mapAdjacent lcp . sort . tails where
lcp (x:xs) (y:ys) | x == y = x : lcp xs ys
lcp _      _               = []
```

Some tests to see if everything is working properly:

```main :: IO ()
main = do print \$ lds "banana"
print \$ lds "ask not what your country can do for you, \
\ask what you can do for your country"
```

Everything seems to be working fine.