Count All Matches
March 10, 2015
Count All Matches
Today’s exercise is an interview question from Google, as reported at Career Cup:
Given two strings, find the number of times the first string occurs in the second, whether continuous or discontinuous. For instance, the string CAT appears in the string CATAPULT three times, as CATapult, CAtapulT, and CatApulT.
Your task is to write the indicated program. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below:
Haskell:
In Python.
(defun count-all-matches (substr text)
(labels ((cam (ss tt)
(let ((count 0))
(cond ((null ss) 1)
((null tt) 0)
(t (loop while (setq tt (member (car ss) tt)) do
(incf count (cam (subseq ss 1) (subseq tt 1)))
(setq tt (subseq tt 1)))
count)))))
(cam (coerce substr ‘list) (coerce text ‘list))))))
My initial C++ solution was like Scott’s, but there were some problems with eg. “count aaaa aaaaaaaa” (the perils of imperative programming). The following seems to works (and when applied to the above, the intermediate arrays of counts make a nice illustration of Pascal’s triangle). It’s sort of a compact memoized/dynamic programming version of the recursive solution (and a good deal more efficient than generating all possible substrings and comparing each one with the target):
My previous solution fails for duplicate letters in the sub string e.g ‘tat’ –> ‘tatapult’. This corrects that mistake
Python.
If t is very long, you might want to preprocess it to remove characters that are not in s.
I think this is equivalent to Francesco’s Haskell:
Another Haskell solution.