Skip to content

Instantly share code, notes, and snippets.

@ijp
Created August 24, 2014 18:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ijp/79cb948ac5dde9fe786d to your computer and use it in GitHub Desktop.
Save ijp/79cb948ac5dde9fe786d to your computer and use it in GitHub Desktop.
import Data.List (tails)
import Data.Map (Map)
import qualified Data.Map as Map
-- <Fuco> heh, this is a nice problem: Given a string A, figure out if string B
-- contains any anagram of A as substring. Example: A = abc, B = de[cab]fh
-- -> true
xs `hasAnagramSubsequence` ys = any (check initialMap) (tails xs)
where initialMap = tabulate ys
check map xs | Map.null map = True
check map [] = False
check map (x : xs) = case Map.lookup x map of
Nothing -> False
Just 1 -> check (Map.delete x map) xs
Just n -> check (Map.insert x (n - 1) map) xs
tabulate :: Ord key => [key] -> Map key Int
tabulate = foldr (\k m -> Map.insertWith (+) k 1 m) Map.empty
-- "decabfh" `hasAnagramSubsequence` "abc"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment