Is there a mathematical way to know exactly how many substrings , prefixes , suffixes does a string have. for example w="abbcc"

1.6k Views Asked by At

My trials were for prefixes and suffixes including the empty string for "abbcc" were equal to the (length_of_the_string + 1) but I couldn't figure out a way for calculating the number of substrings .

1

There are 1 best solutions below

2
On

Do you mean how many distinct substrings or do you allow duplicates? If you wish to count distinct substrings, the answer depends on the particular string. I will address the latter question, the number of substrings allowing duplicates.

A substring is defined by a start index and an end index. Let the start index be the index of the first character in the substring and the end index be the index of the first character after the end of the string. Index characters starting at 1 (so the first character has index 1).

If a string has length $n$, there are $n+1$ possible start indices ranging from 1 to $n+1$ where $n+1$ means the substring starts after the end of the string (and thus must be empty). Given a start index $s$, there are $n+2-s$ possible end indices ranging from $s$ to $n+1$, meaning $n+2-s$ substrings starting at index $s$. You must sum this quantity over all possible choices of $s$:

$$\sum_{s=1}^{n+1}n+2-s = (n+1)(n+2) - \frac{(n+1)(n+2)}{2} = \frac{(n+1)(n+2)}{2}.$$