Check if string follows order of characters defined by a pattern or not | Set 3 | Javascript program to find if a string follows order defined by a given pattern . ; Returns true if characters of str follow order defined by a given ptr . ; Initialize all orders as - 1 ; Assign an order to pattern characters according to their appearance in pattern ; give the pattern characters order ; increment the order ; Now one by check if string characters follow above order ; If order of this character is less than order of previous , return false . ; Update last_order for next iteration ; return that str followed pat ; Driver code
let CHAR_SIZE = 256 ; function checkPattern ( str , pat ) { let label = new Array ( CHAR_SIZE ) ; for ( let i = 0 ; i < CHAR_SIZE ; i ++ ) label [ i ] = - 1 ; let order = 1 ; for ( let i = 0 ; i < pat . length ; i ++ ) { label [ pat [ i ] . charCodeAt ( 0 ) ] = order ; order ++ ; } let last_order = - 1 ; for ( let i = 0 ; i < str . length ; i ++ ) { if ( label [ str [ i ] . charCodeAt ( 0 ) ] != - 1 ) { if ( label [ str [ i ] . charCodeAt ( 0 ) ] < last_order ) return false ; last_order = label [ str [ i ] . charCodeAt ( 0 ) ] ; } } return true ; } let str = " " ; let pattern = " " ; document . write ( checkPattern ( str , pattern ) ) ;