Remove all occurrences of a word from a given string using Z | Java program for the above approach ; Function to fill the Z - array for str ; L Stores start index of window which matches with prefix of str ; R Stores end index of window which matches with prefix of str ; Iterate over the characters of str ; If i is greater thn R ; Update L and R ; If subString match with prefix ; Update R ; Update Z [ i ] ; Update R ; Update k ; if Z [ k ] is less than remaining interval ; Update Z [ i ] ; Start from R and check manually ; Update R ; Update Z [ i ] ; Update R ; Function to remove all the occurrences of word from str ; Create concatenated String " P $ T " ; Store Z array of concat ; Stores String , str by removing all the occurrences of word from str ; Stores length of word ; Traverse the array , Z [ ] ; if Z [ i + pSize + 1 ] equal to length of word ; Update i ; Driver Code
import java . util . * ; class GFG { static void getZarr ( String str , int Z [ ] ) { int n = str . length ( ) ; int k ; int L = 0 ; int R = 0 ; for ( int i = 1 ; i < n ; ++ i ) { if ( i > R ) { L = R = i ; while ( R < n && str . charAt ( R - L ) == str . charAt ( R ) ) { R ++ ; } Z [ i ] = R - L ; R -- ; } else { k = i - L ; if ( Z [ k ] < R - i + 1 ) { Z [ i ] = Z [ k ] ; } else { L = i ; while ( R < n && str . charAt ( R - L ) == str . charAt ( R ) ) { R ++ ; } Z [ i ] = R - L ; R -- ; } } } } static String goodStr ( String str , String word ) { String concat = word + " $ " + str ; int l = concat . length ( ) ; int [ ] Z = new int [ l ] ; getZarr ( concat , Z ) ; String res = " " ; int pSize = word . length ( ) ; for ( int i = 0 ; i < l ; ++ i ) { if ( i + pSize < l - 1 && Z [ i + pSize + 1 ] == pSize ) { i += pSize - 1 ; } else if ( i < str . length ( ) ) { res += str . charAt ( i ) ; } } return res ; } public static void main ( String [ ] args ) { String str = " Z - kmalgorithmkmiskmkmkmhelpfulkminkmsearching " ; String word = " km " ; System . out . print ( goodStr ( str , word ) ) ; } }