Given a simple sentence and a set of syntax rules, validate if it is syntactically correct or not.

Assume that a sentence is syntactically correct if it fulfills the following rules:

  • A sentence must start with an uppercase character.
  • There must be spaces between words.
  • Then the sentence must end with a full stop (.).
  • Two continuous spaces are not allowed.
  • Two continuous uppercase characters are not allowed.
  • However, the sentence can end after an uppercase character.

 
For example,

“This sentence is syntactically correct.”
 
“This sentence is syntactically incorrect as two continuous spaces are not allowed.”
 
“This sentence is syntactically correct Y.”
 
“This sentence is syntactically incorRect as uppercase character is not allowed midway of the string.”
 
“THis sentence is syntactically incorrect as two continuous uppercase characters are not allowed.”
 
“This sentence is syntactically incorrect as it doesn’t end with a full stop”

The idea is to scan the given string and check for the above rules by comparing adjacent characters. Return false if any of the given constraints gets violated. Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
The valid sentences are:
 
This sentence is syntactically correct.
This sentence is syntactically correct Y.

The time complexity of the above solution is O(n), where n is the length of the input string and doesn’t require any extra space.