human
Count all substrings having character K | Function to return the index of the next occurrence of character ch in strr starting from the given index.
Return the index of the first occurrence of ch.
No occurrence found.
Function to return the count of all the substrings of strr which contain the character ch at least one.
To store the count of valid substrings.
Index of the first occurrence of ch in strr.
No occurrence of ch after index i in strr.
Substrings starting at index i and ending at indices j , j + 1 , ... , n - 1 are all valid substring.
Driver code"
How can the above be solved in Python?
assistant
#Here is code to count all substrings having character K and the other steps required.
 def nextOccurrence ( strr , n , start , ch ) :
	for i in range ( start , n ) :
		if ( strr [ i ] == ch ) :
			return i
	return - 1
def countSubStr ( strr , n , ch ) :
	cnt = 0
	j = nextOccurrence ( strr , n , 0 , ch )
	for i in range ( n ) :
		while ( j != - 1 and j < i ) :
			j = nextOccurrence ( strr , n , j + 1 , ch )
		if ( j == - 1 ) :
			break
		cnt += ( n - j )
	return cnt
strr = " geeksforgeeks "
n = len ( strr )
ch = ' k '
print ( countSubStr ( strr , n , ch ) )