Solution to the counting substrings problem.