Check a given sentence for a given set of simple grammer rules | Method to check a given sentence for given rules ; Calculate the length of the string . ; Check that the first character lies in [ A - Z ] . Otherwise return false . ; If the last character is not a full stop ( . ) no need to check further . ; Maintain 2 states . Previous and current state based on which vertex state you are . Initialise both with 0 = start state . ; Keep the index to the next character in the string . ; Loop to go over the string . ; Set states according to the input characters in the string and the rule defined in the description . If current character is [ A - Z ] . Set current state as 0. ; If current character is a space . Set current state as 1. ; If current character is [ a - z ] . Set current state as 2. ; If current state is a dot ( . ) . Set current state as 3. ; Validates all current state with previous state for the rules in the description of the problem . ; If we have reached last state and previous state is not 1 , then check next character . If next character is ' \0' , then return true , else false ; Set previous state as current state before going over to the next character . ; Driver Code
function checkSentence ( str ) { var len = str . length ; if ( str [ 0 ] . charCodeAt ( 0 ) < " " . charCodeAt ( 0 ) || str [ 0 ] . charCodeAt ( 0 ) > " " . charCodeAt ( 0 ) ) return false ; if ( str [ len - 1 ] !== " " ) return false ; var prev_state = 0 , curr_state = 0 ; var index = 1 ; while ( index <= str . length ) { if ( str [ index ] . charCodeAt ( 0 ) >= " " . charCodeAt ( 0 ) && str [ index ] . charCodeAt ( 0 ) <= " " . charCodeAt ( 0 ) ) curr_state = 0 ; else if ( str [ index ] === " " ) curr_state = 1 ; else if ( str [ index ] . charCodeAt ( 0 ) >= " " . charCodeAt ( 0 ) && str [ index ] . charCodeAt ( 0 ) <= " " . charCodeAt ( 0 ) ) curr_state = 2 ; else if ( str [ index ] === " " ) curr_state = 3 ; if ( prev_state === curr_state && curr_state !== 2 ) return false ; if ( prev_state === 2 && curr_state === 0 ) return false ; if ( curr_state === 3 && prev_state !== 1 ) return index + 1 == str . length ; index ++ ; prev_state = curr_state ; } return false ; } var str = [ " " , " " , " " , " " , " " , " " , " " , " " , " " , ] ; var str_size = str . length ; var i = 0 ; for ( i = 0 ; i < str_size ; i ++ ) { var temp = str [ i ] . split ( " " ) ; if ( checkSentence ( temp ) ) document . write ( ' ' + str [ i ] + ' ' + " " + " " ) ; else document . write ( ' ' + str [ i ] + ' ' + " " + " " ) ; }