Given a string and we have to calculate the number of all possible substrings of length 1 to n.
给定一个字符串,我们必须计算长度为1到n的所有可能子字符串的数量。
This can be done by two ways:
这可以通过两种方式完成:
1) By General Method
1)一般方法
In this method, we first calculate all the possible substring by using nested for loops. After that count all the substring that we calculated. But this process is time-consuming and takes a lot of time if the length of the string exceeds too much.
在这种方法中,我们首先使用嵌套的for循环计算所有可能的子字符串。 之后,计算我们计算的所有子字符串。 但是,此过程很耗时,并且如果字符串的长度超过太多,则会花费大量时间。
Time Complexity : O(n*n) , n is the length of the string
时间复杂度 : O(n * n) , n是字符串的长度
2) By Formula
2)按公式
In this method, we can simply calculate the total number of possible substrings by a formula.
在这种方法中,我们可以简单地通过公式计算可能的子字符串的总数。
Total number of substrings:
子字符串总数:
n + (n-1) + (n-2) + ... + 3 + 2 + 1
= n * (n + 1) / 2
Time Complexity : O(1), ... Constant order
时间复杂度 : O(1) ,...恒定阶
Note: It is not recommended that one should calculate the number of substring by General method because for larger strings system may become non-responsive. So use the formula to calculate the number of substrings.
注意:建议不要使用常规方法计算子字符串的数目,因为对于较大的字符串,系统可能会变得无响应。 因此,请使用公式来计算子字符串的数量。
Python代码来计算字符串的子字符串数 (Python code to count number of substrings of a string)
def count_substr_by_formula(string):
'''
This function is used to calculate
number of all possible substring of
a string by a formula.
'''
substring = 0
# length of the given string
n = len(string)
substring = n * (n + 1) // 2
return substring
# Time Complexity : O(1) {constant order}
def general_method(string):
'''
This function is used to calculate
number of all possible substring of
a string by using nested for loops.
'''
substring = 0
n = len(string)
# List to store all the calculated substrings
substr = []
for i in range(n):
for j in range(i,n):
substr.append(string[i:j])
substring = len(substr)
return substring
# Time Complexity : O(n*n)
# Main Code
if __name__=='__main__':
string = 'IncludeHelp'
print('Total number of substring = %d' % count_substr_by_formula(string))
print('Total number of substring = %d' % general_method(string))
Output
输出量
Total number of substring = 66
Total number of substring = 66
翻译自: https://www.includehelp.com/python/calculate-the-number-of-all-possible-substrings-of-a-string.aspx