Optimized Naive Algorithm for Pattern Searching | A modified Naive Pettern Searching algorithn that is optimized for the cases when all characters of pattern are different ; For current index i , check for pattern match ; if pat [ 0. . . M - 1 ] = txt [ i , i + 1 , ... i + M - 1 ] ; slide the pattern by j ; Driver Code
< ? php function search ( $ pat , $ txt ) { $ M = strlen ( $ pat ) ; $ N = strlen ( $ txt ) ; $ i = 0 ; while ( $ i <= $ N - $ M ) { $ j ; for ( $ j = 0 ; $ j < $ M ; $ j ++ ) if ( $ txt [ $ i + $ j ] != $ pat [ $ j ] ) break ; if ( $ j == $ M ) { echo ( " Pattern ▁ found ▁ at ▁ index ▁ $ i " . " STRNEWLINE " ) ; $ i = $ i + $ M ; } else if ( $ j == 0 ) $ i = $ i + 1 ; else $ i = $ i + $ j ; } } $ txt = " ABCEABCDABCEABCD " ; $ pat = " ABCD " ; search ( $ pat , $ txt ) ; ? >