Check if string follows order of characters defined by a pattern or not | Set 2 | Javascript program to check if characters of a string follow pattern defined by given pattern . ; Insert all characters of pattern in a hash set , ; Build modified string ( string with characters only from pattern are taken ) ; Remove more than one consecutive occurrences of pattern characters from modified string . ; After above modifications , the length of modified string must be same as pattern length ; And pattern characters must also be same as modified string characters ; Driver program
function followsPattern ( str , pattern ) { let patternSet = new Set ( ) ; for ( let i = 0 ; i < pattern . length ; i ++ ) patternSet . add ( pattern [ i ] ) ; let modifiedString = ( str ) . split ( " " ) ; for ( let i = str . length - 1 ; i >= 0 ; i -- ) if ( ! patternSet . has ( modifiedString [ i ] ) ) modifiedString . splice ( i , 1 ) ; for ( let i = modifiedString . length - 1 ; i > 0 ; i -- ) if ( modifiedString [ i ] == modifiedString [ i - 1 ] ) modifiedString . splice ( i , 1 ) ; if ( pattern . length != modifiedString . length ) return false ; for ( let i = 0 ; i < pattern . length ; i ++ ) if ( pattern [ i ] != modifiedString [ i ] ) return false ; return true ; } let str = " " ; let pattern = " " ; document . write ( " " + followsPattern ( str , pattern ) + " " ) ; str = " " ; pattern = " " ; document . write ( " " + followsPattern ( str , pattern ) + " " ) ; str = " " ; pattern = " " ; document . write ( " " + followsPattern ( str , pattern ) + " " ) ; str = " " ; pattern = " " ; document . write ( " " + followsPattern ( str , pattern ) + " " ) ;