algorithm - Why is the total number of possible substrings of a string n^2? -
i read total number of substrings can formed given string n^2 don't understand how count this.
by substrings, mean, given string cat, substrings be:
c ca cat @ t
the total number of (nonempty) substrings n + c(n,2)
. leading n
counts number of substrings of length 1 , c(n,2)
counts number of substrings of length > 1 , equal number of ways choose 2 indices set of n
. standard formula binomial coefficients yields c(n,2) = n*(n-1)/2
. combining these 2 terms , simplifying gives total number (n^2 + n)/2
. @rici in comments notes same c(n+1,2)
makes sense if e.g. think in terms of python string slicing substrings of s
can written in form s[i:j]
0 <= < j <= n
(with j
being 1 more final index). n = 3
works out (9 + 3)/2 = 6
.
in sense of complexity theory number of substrings is o(n^2)
, might read somewhere.
Comments
Post a Comment