Remove last occurrence of a word from a given sentence string | Function to remove last occurrence of W from S ; If M is greater than N ; Iterate while i is greater than or equal to 0 ; of W has been found or not ; Iterate over the range [ 0 , M ] ; If S [ j + 1 ] is not equal to W [ j ] ; Mark flag true and break ; If occurrence has been found ; Delete the subover the range [ i , i + M ] ; Resize the S ; Return S ; Driver Code ; Input ; Function call
def removeLastOccurrence ( S , W , N , M ) : NEW_LINE INDENT S = [ i for i in S ] NEW_LINE W = [ i for i in W ] NEW_LINE if ( M > N ) : NEW_LINE INDENT return S NEW_LINE DEDENT for i in range ( N - M , - 1 , - 1 ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( M ) : NEW_LINE INDENT if ( S [ j + i ] != W [ j ] ) : NEW_LINE INDENT flag = 1 NEW_LINE break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT for j in range ( i , N - M ) : NEW_LINE INDENT S [ j ] = S [ j + M ] NEW_LINE DEDENT S = S [ : N - M ] NEW_LINE break NEW_LINE DEDENT DEDENT return " " . join ( S ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT S = " This ▁ is ▁ GeeksForGeeks " NEW_LINE W = " Geeks " NEW_LINE N = len ( S ) NEW_LINE M = len ( W ) NEW_LINE print ( removeLastOccurrence ( S , W , N , M ) ) NEW_LINE DEDENT