Check a given sentence for a given set of simple grammer rules

A simple sentence if syntactically correct if it fulfills given rules. The following are given rules.

1. Sentence must start with a Uppercase character (e.g. Noun/ I/ We/ He etc.)
2. Then lowercase character follows.
3. There must be spaces between words.
4. Then the sentence must end with a full stop(.) after a word.
5. Two continuous spaces are not allowed.
6. Two continuous upper case characters are not allowed.
7. However, the sentence can end after an upper case character.

Question: Given a sentence, validate the given sentence for above given rules.

We strongly recommend to minimize the browser and try this yourself first.
The idea is to use an automata for the given set of rules.

Algorithm :
1. Check for the corner cases
…..1.a) Check if the first character is uppercase or not in the sentence.
…..1.b) Check if the last character is a full stop or not.

2. For rest of the string, this problem could be solved by following a state diagram. Please refer to the below state diagram for that.

3. We need to maintain previous and current state of different characters in the string. Based on that we can always validate the sentence of every character traversed.

A C based implementation is below. (By the way this sentence is also correct according to the rule and code)

C++

filter_none

editclose

play_arrow

linkbrightness_4code

// C program to validate a given sentence for a set of rules

#include<stdio.h>

#include<string.h>

#include<stdbool.h>

// Method to check a given sentence for given rules

boolcheckSentence(charstr[])

{

// Calculate the length of the string.

intlen = strlen(str);

// Check that the first character lies in [A-Z].

// Otherwise return false.

if(str[0] < 'A'|| str[0] > 'Z')

returnfalse;

//If the last character is not a full stop(.) no

//need to check further.

if(str[len - 1] != '.')

returnfalse;

// Maintain 2 states. Previous and current state based

// on which vertex state you are. Initialise both with

// 0 = start state.

intprev_state = 0, curr_state = 0;

//Keep the index to the next character in the string.

intindex = 1;

//Loop to go over the string.

while(str[index])

{

// 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(str[index] >= 'A'&& str[index] <= 'Z')

curr_state = 0;

// If current character is a space. Set current state as 1.

elseif(str[index] == ' ')

curr_state = 1;

// If current character is [a-z]. Set current state as 2.

elseif(str[index] >= 'a'&& str[index] <= 'z')

curr_state = 2;

// If current state is a dot(.). Set current state as 3.

elseif(str[index] == '.')

curr_state = 3;

// Validates all current state with previous state for the

// rules in the description of the problem.

if(prev_state == curr_state && curr_state != 2)

returnfalse;

if(prev_state == 2 && curr_state == 0)

returnfalse;

// 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

if(curr_state == 3 && prev_state != 1)

return(str[index + 1] == '\0');

index++;

// Set previous state as current state before going over

// to the next character.

prev_state = curr_state;

}

returnfalse;

}

// Driver program

intmain()

{

char*str[] = { "I love cinema.", "The vertex is S.",

"I am single.", "My name is KG.",

"I lovE cinema.", "GeeksQuiz. is a quiz site.",

"I love Geeksquiz and Geeksforgeeks.",

" You are my friend.", "I love cinema"};

intstr_size = sizeof(str) / sizeof(str[0]);

inti = 0;

for(i = 0; i < str_size; i++)

checkSentence(str[i])? printf("\"%s\" is correct \n", str[i]):

printf("\"%s\" is incorrect \n", str[i]);

return0;

}

chevron_right

filter_none

Java

filter_none

editclose

play_arrow

linkbrightness_4code

// Java program to validate a given sentence

// for a set of rules

classGFG

{

// Method to check a given sentence for given rules

staticbooleancheckSentence(char[] str)

{

// Calculate the length of the string.

intlen = str.length;

// Check that the first character lies in [A-Z].

// Otherwise return false.

if(str[0] < 'A'|| str[0] > 'Z')

returnfalse;

// If the last character is not a full stop(.)

// no need to check further.

if(str[len - 1] != '.')

returnfalse;

// Maintain 2 states. Previous and current state

// based on which vertex state you are.

// Initialise both with 0 = start state.

intprev_state = 0, curr_state = 0;

// Keep the index to the next character in the string.

intindex = 1;

// Loop to go over the string.

while(index <= str.length)

{

// 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(str[index] >= 'A'&& str[index] <= 'Z')

curr_state = 0;

// If current character is a space.

// Set current state as 1.

elseif(str[index] == ' ')

curr_state = 1;

// If current character is [a-z].

// Set current state as 2.

elseif(str[index] >= 'a'&& str[index] <= 'z')

curr_state = 2;

// If current state is a dot(.).

// Set current state as 3.

elseif(str[index] == '.')

curr_state = 3;

// Validates all current state with previous state

// for the rules in the description of the problem.

if(prev_state == curr_state && curr_state != 2)

returnfalse;

if(prev_state == 2&& curr_state == 0)

returnfalse;

// 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

if(curr_state == 3&& prev_state != 1)

return(index + 1== str.length);

index++;

// Set previous state as current state

// before going over to the next character.

prev_state = curr_state;

}

returnfalse;

}

// Driver Code

publicstaticvoidmain(String[] args)

{

String[] str = { "I love cinema.", "The vertex is S.",

"I am single.", "My name is KG.",

"I lovE cinema.", "GeeksQuiz. is a quiz site.",

"I love Geeksquiz and Geeksforgeeks.",

" You are my friend.", "I love cinema"};

intstr_size = str.length;

inti = 0;

for(i = 0; i < str_size; i++)

{

if(checkSentence(str[i].toCharArray()))

System.out.println("\""+ str[i] +

"\""+ " is correct");

else

System.out.println("\""+ str[i] +

"\""+ " is incorrect");

}

}

}

// This code is contributed by

// sanjeev2552

chevron_right

filter_none

Python

filter_none

editclose

play_arrow

linkbrightness_4code

# Python program to validate a given sentence for a set of rules

# Method to check a given sentence for given rules

defcheckSentence(string):

# Calculate the length of the string.

length =len(string)

# Check that the first character lies in [A-Z].

# Otherwise return false.

ifstring[0] < 'A'orstring[0] > 'Z':

returnFalse

# If the last character is not a full stop(.) no

# need to check further.

ifstring[length-1] !='.':

returnFalse

# Maintain 2 states. Previous and current state based

# on which vertex state you are. Initialise both with

# 0 = start state.

prev_state =0

curr_state =0

# Keep the index to the next character in the string.

index =1

# Loop to go over the string.

while(string[index]):

# 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.

ifstring[index] >='A'andstring[index] <='Z':

curr_state =0

# If current character is a space. Set current state as 1.

elifstring[index] ==' ':

curr_state =1

# If current character is a space. Set current state as 2.

elifstring[index] >='a'andstring[index] <='z':

curr_state =2

# If current character is a space. Set current state as 3.

elifstring[index] =='.':

curr_state =3

# Validates all current state with previous state for the

# rules in the description of the problem.

ifprev_state ==curr_state andcurr_state !=2:

returnFalse

# 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

ifprev_state ==2andcurr_state ==0:

returnFalse

# Set previous state as current state before going over

# to the next character.

ifcurr_state ==3andprev_state !=1:

returnTrue

index +=1

prev_state =curr_state

returnFalse

# Driver program

string =["I love cinema.", "The vertex is S.",

"I am single.", "My name is KG.",

"I lovE cinema.", "GeeksQuiz. is a quiz site.",

"I love Geeksquiz and Geeksforgeeks.",

" You are my friend.", "I love cinema"]

string_size =len(string)

fori inxrange(string_size):

ifcheckSentence(string[i]):

print"\""+string[i] +"\" is correct"

else:

print"\""+string[i] +"\" is incorrect"

# This code is contributed by BHAVYA JAIN

chevron_right

filter_none

C#

filter_none

editclose

play_arrow

linkbrightness_4code

// C# program to validate a given sentence

// for a set of rules

usingSystem;

classGFG

{

// Method to check a given sentence for given rules

staticboolcheckSentence(char[] str)

{

// Calculate the length of the string.

intlen = str.Length;

// Check that the first character lies in [A-Z].

// Otherwise return false.

if(str[0] < 'A'|| str[0] > 'Z')

returnfalse;

// If the last character is not a full stop(.)

// no need to check further.

if(str[len - 1] != '.')

returnfalse;

// Maintain 2 states. Previous and current state

// based on which vertex state you are.

// Initialise both with 0 = start state.

intprev_state = 0, curr_state = 0;

// Keep the index to the next character in the string.

intindex = 1;

// Loop to go over the string.

while(index <= str.Length)

{

// 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(str[index] >= 'A'&& str[index] <= 'Z')

curr_state = 0;

// If current character is a space.

// Set current state as 1.

elseif(str[index] == ' ')

curr_state = 1;

// If current character is [a-z].

// Set current state as 2.

elseif(str[index] >= 'a'&& str[index] <= 'z')

curr_state = 2;

// If current state is a dot(.).

// Set current state as 3.

elseif(str[index] == '.')

curr_state = 3;

// Validates all current state with previous state

// for the rules in the description of the problem.

if(prev_state == curr_state && curr_state != 2)

returnfalse;

if(prev_state == 2 && curr_state == 0)

returnfalse;

// 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

if(curr_state == 3 && prev_state != 1)

return(index + 1 == str.Length);

index++;

// Set previous state as current state

// before going over to the next character.

prev_state = curr_state;

}

returnfalse;

}

// Driver Code

publicstaticvoidMain(String[] args)

{

String[] str = { "I love cinema.", "The vertex is S.",

"I am single.", "My name is KG.",

"I lovE cinema.", "GeeksQuiz. is a quiz site.",

"I love Geeksquiz and Geeksforgeeks.",

" You are my friend.", "I love cinema"};

intstr_size = str.Length;

inti = 0;

for(i = 0; i < str_size; i++)

{

if(checkSentence(str[i].ToCharArray()))

Console.WriteLine("\""+ str[i] +

"\""+ " is correct");

else

Console.WriteLine("\""+ str[i] +

"\""+ " is incorrect");

}

}

}

// This code is contributed by 29AjayKumar

chevron_right

filter_none

Output:

"I love cinema." is correct
"The vertex is S." is correct
"I am single." is correct
"My name is KG." is incorrect
"I lovE cinema." is incorrect
"GeeksQuiz. is a quiz site." is incorrect
"I love Geeksquiz and Geeksforgeeks." is correct
" You are my friend." is incorrect
"I love cinema" is incorrect

Time complexity – O(n), worst case as we have to traverse the full sentence where n is the length of the sentence.Auxiliary space – O(1)

This article is contributed by Kumar Gautam. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details