Check if string follows order of characters defined by a pattern or not | Set 1 | Function to check if characters in the input string follows the same order as determined by characters present in the given pattern ; len stores length of the given pattern ; if length of pattern is more than length of input string , return false ; ; x , y are two adjacent characters in pattern ; find index of last occurrence of character x in the input string ; find index of first occurrence of character y in the input string ; return false if x or y are not present in the input string OR last occurrence of x is after the first occurrence of y in the input string ; return true if string matches the pattern ; Driver code
function checkPattern ( str , pattern ) { var len = pattern . length ; if ( str . length < len ) { return false ; } for ( var i = 0 ; i < len - 1 ; i ++ ) { var x = pattern [ i ] ; var y = pattern [ i + 1 ] ; var last = str . lastIndexOf ( x ) ; var first = str . indexOf ( y ) ; if ( last === - 1 first === - 1 last > first ) { return false ; } } return true ; } var str = " " ; var pattern = " " ; document . write ( checkPattern ( str , pattern ) ) ;