Minimum characters to be replaced to remove the given substring | Function to calculate minimum characters to replace ; mismatch occurs ; If all characters matched , i . e , there is a substring of ' a ' which is same as string ' b ' ; increment i to index m - 1 such that minimum characters are replaced in ' a ' ; Driver Code
def replace ( A , B ) : NEW_LINE INDENT n , m = len ( A ) , len ( B ) NEW_LINE count , i = 0 , 0 NEW_LINE while i < n : NEW_LINE INDENT j = 0 NEW_LINE while j < m : NEW_LINE INDENT if i + j >= n or A [ i + j ] != B [ j ] : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT if j == m : NEW_LINE INDENT count += 1 NEW_LINE i += m - 1 NEW_LINE DEDENT i += 1 NEW_LINE DEDENT return count NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = " aaaaaaaa " NEW_LINE str2 = " aaa " NEW_LINE print ( replace ( str1 , str2 ) ) NEW_LINE DEDENT