Given string str, the task is to check if this string str consists of valid English words or not.
A string is known as a valid English word if it meets all the below criteria-
- The string can have an uppercase character as the first character only.
- The string can only have lowercase characters.
- The string can consist of only one hyphen(‘-‘) surrounded by characters on both ends.
- The string cannot consist of any digits.
- If there is any punctuation mark it must be only one and it must be present at the end.
Print the number of valid words in the string str.
Input: str = “i Love- Geeks-forgeeks!”
Output: 1 word
Explanation:
word 1 = “i” does not contain first uppercase character, it is not valid word
word 2 = “Love-” hyphen is not surrounded by characters on both ends, it is not valid word
word 3 = “Geeks-forgeeks!” is a valid word
Input: str = “!this 1-s b8d!”
Output: 0 words
Explanation:
word 1 = “!this” punctuation mark is in the beginning, it is not valid word
word 2 = “1-s” digit as first character, it is not valid word
word 3 = “b8d!” first character is not uppercase, it is not valid word
Approach:
- Initialize the variable ans to keep count of the number of valid words.
- Loop through each word present in the sentence.
- Check each letter of the word to see if it meets the criteria mentioned in the problem statement.
- If any of the criteria is not met then return false.
- If all the criteria are satisfied by the word, then increment the value of the variable ans.
- Print the value of the variable ans.
Below is the C++ program of the above approach-
C++
#include <bits/stdc++.h>
using namespace std;
bool ValidWords(string sentence)
{
int hyphen = 0;
int size = sentence.size();
if ( isupper (sentence[0])) {
for ( int i = 0; i < size; i++) {
if ( isdigit (sentence[i]))
return false ;
if ( isupper (sentence[i]))
return false ;
if ( isalpha (sentence[i]))
continue ;
if (sentence[i] == '-' ) {
if (++hyphen > 1)
return false ;
if (i - 1 < 0
|| ! isalpha (sentence[i - 1])
|| i + 1 >= size
|| ! isalpha (sentence[i + 1]))
return false ;
}
else if (i != size - 1
&& ispunct(sentence[i]))
return false ;
}
}
else
return true ;
}
int main()
{
string sentence = "i Love- Geeks-Forgeeks!" ;
istringstream s(sentence);
string word;
int ans = 0;
while (s >> word)
if (ValidWords(word))
ans++;
cout << ans << " words" ;
}
|
Java
import java.io.*;
class GFG {
static boolean ValidWords(String sentence)
{
int hyphen = 0 ;
int size = sentence.length();
if (Character.isUpperCase(sentence.charAt( 0 ))) {
for ( int i = 0 ; i < size; i++) {
if (Character.isDigit(sentence.charAt(i)))
return false ;
if (Character.isUpperCase(
sentence.charAt(i)))
return false ;
if (Character.isAlphabetic(
sentence.charAt(i)))
continue ;
if (sentence.charAt(i) == '-' ) {
hyphen = hyphen + 1 ;
if (hyphen > 1 )
return false ;
if (i - 1 < 0
|| !Character.isAlphabetic(
sentence.charAt(i - 1 ))
|| i + 1 >= size
|| !Character.isAlphabetic(
sentence.charAt(i + 1 )))
return false ;
}
else if (i != size - 1
&& ((sentence.charAt(i) == '!'
|| sentence.charAt(i) == ','
|| sentence.charAt(i) == ';'
|| sentence.charAt(i) == '.'
|| sentence.charAt(i) == '?'
|| sentence.charAt(i) == '-'
|| sentence.charAt(i) == '\''
|| sentence.charAt(i) == '\"'
|| sentence.charAt(i)
== ':' )))
return false ;
}
}
else
return true ;
return false ;
}
public static void main(String[] args)
{
String sentence = "i Love- Geeks-Forgeeks!" ;
int ans = 0 ;
String words[] = sentence.split( " " );
for (String word : words) {
if (ValidWords(word)== true ){
ans++;
}
}
System.out.print(ans + " words" );
}
}
|
Python3
def ValidWords(sentence):
hyphen = 0
size = len (sentence)
if (sentence[ 0 ] > = 'A' and sentence[ 0 ] < = 'Z' ):
for i in range (size):
if (sentence[i] > = '0' and sentence[i] < = '9' ):
return False
if (sentence[i] > = 'A' and sentence[i] < = 'Z' ):
return False
if (sentence[i] > = 'a' and sentence[i] < = 'z' or sentence[i] > = 'A'
and sentence[i] < = 'Z' ):
continue
if (sentence[i] = = '-' ):
if (hyphen + 1 > 1 ):
return False
if (i - 1 < 0 or ~(sentence[i - 1 ] > = 'a' and
sentence[i - 1 ] < = 'z' or sentence[i - 1 ] > = 'A'
and sentence[i - 1 ] < = 'Z' ) or i + 1 > = size or
~(sentence[i + 1 ] > = 'a' and sentence[i + 1 ] < = 'z'
or sentence[i + 1 ] > = 'A' and sentence[i + 1 ] < = 'Z' )):
return False
elif (i ! = size - 1 and ((sentence[i] = = '!' or sentence[i] = = ','
or sentence[i] = = ';' or sentence[i] = = '.' or sentence[i] = = '?'
or sentence[i] = = '-' or sentence[i] = = '\'' or sentence[i] = = '\"'
or sentence[i] = = ':' ))):
return False
else :
return True
sentence = "i Love- Geeks-Forgeeks!"
word = sentence.split( ' ' )
ans = 0
for indx in word :
if (ValidWords(indx)):
ans + = 1
print (f "{ans} words" )
|
C#
using System;
class GFG
{
static bool ValidWords(String sentence)
{
int hyphen = 0;
int size = sentence.Length;
if ( char .IsUpper(sentence[0]))
{
for ( int i = 0; i < size; i++)
{
if ( char .IsDigit(sentence[i]))
return false ;
if ( char .IsUpper(sentence[i]))
return false ;
if ( char .IsLetter(sentence[i]))
continue ;
if (sentence[i] == '-' )
{
hyphen = hyphen + 1;
if (hyphen > 1)
return false ;
if (i - 1 < 0
|| ! char .IsLetter(sentence[i - 1])
|| i + 1 >= size
|| ! char .IsLetter(sentence[i + 1]))
return false ;
}
else if (i != size - 1
&& ((sentence[i] == '!'
|| sentence[i] == ','
|| sentence[i] == ';'
|| sentence[i] == '.'
|| sentence[i] == '?'
|| sentence[i] == '-'
|| sentence[i] == '\''
|| sentence[i] == '\"'
|| sentence[i]
== ':' )))
return false ;
}
}
else
return true ;
return false ;
}
public static void Main()
{
String sentence = "i Love- Geeks-Forgeeks!" ;
int ans = 0;
String[] words = sentence.Split( " " );
foreach (String word in words)
{
if (ValidWords(word) == true )
{
ans++;
}
}
Console.Write(ans + " words" );
}
}
|
Javascript
<script>
const ValidWords = (sentence) => {
let hyphen = 0;
let size = sentence.length;
if (sentence[0] >= 'A' && sentence[0] <= 'Z' )
{
for (let i = 0; i < size; i++)
{
if (sentence[i] >= '0' && sentence[i] <= '9' )
return false ;
if (sentence[i] >= 'A' && sentence[i] <= 'Z' )
return false ;
if (sentence[i] >= 'a' && sentence[i] <= 'z' ||
sentence[i] >= 'A' && sentence[i] <= 'Z' )
continue ;
if (sentence[i] == '-' ) {
if (++hyphen > 1)
return false ;
if (i - 1 < 0
|| !(sentence[i - 1] >= 'a' &&
sentence[i - 1] <= 'z' ||
sentence[i - 1] >= 'A' &&
sentence[i - 1] <= 'Z' )
|| i + 1 >= size
|| !(sentence[i + 1] >= 'a' &&
sentence[i + 1] <= 'z' ||
sentence[i + 1] >= 'A' &&
sentence[i + 1] <= 'Z' ))
return false ;
}
else if (i != size - 1
&& ((sentence[i] == '!'
|| sentence[i] == ','
|| sentence[i] == ';'
|| sentence[i] == '.'
|| sentence[i] == '?'
|| sentence[i] == '-'
|| sentence[i] == '\''
|| sentence[i] == '\"'
|| sentence[i]
== ':' )))
return false ;
}
}
else
return true ;
}
let sentence = "i Love- Geeks-Forgeeks!";
let word = sentence.split( ' ' );
let ans = 0;
for (let indx in word)
if (ValidWords(word[indx]))
ans++;
document.write(`${ans} words`);
</script>
|
Time Complexity: O(N) as only one traversal of the string of length N is enough for the algorithm to perform all the tasks hence the overall complexity is linear.
Auxiliary Space: O(N) as the variable s stores all the words of the strings hence the overall space occupied by the algorithm is equal to the length of the string
Approach 2:
Here is another approach to check for valid words in a given sentence:
- Split the sentence into words using whitespace as a delimiter.
- For each word, iterate over its characters and perform the following checks:
- The first character should be an uppercase or lowercase letter.
- All other characters should be lowercase letters or hyphens.
- There should be at most one hyphen, and it should not be the first or last character.
- There should be no digits or punctuation marks.
- If a word passes all the checks, increment a counter to keep track of the number of valid words.
After processing all the words in the sentence, display the number of valid words found.
Here is an implementation of this approach in C++:
C++
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
bool isValidWord( const string& word) {
if (word.empty()) {
return false ;
}
if (! isalpha (word[0])) {
return false ;
}
int hyphenCount = 0;
for ( int i = 1; i < word.length(); i++) {
if (word[i] == '-' ) {
hyphenCount++;
if (hyphenCount > 1 || i == 1 || i == word.length() - 1 || ! isalpha (word[i - 1]) || ! isalpha (word[i + 1])) {
return false ;
}
}
else if (! islower (word[i])) {
return false ;
}
}
return true ;
}
int countValidWords( const string& sentence) {
int count = 0;
string word;
for ( int i = 0; i < sentence.length(); i++) {
if ( isspace (sentence[i])) {
if (isValidWord(word)) {
count++;
}
word.clear();
}
else {
word += sentence[i];
}
}
if (isValidWord(word)) {
count++;
}
return count;
}
int main() {
string sentence = "i Love- Geeks-Forgeeks!" ;
int validWordCount = countValidWords(sentence);
cout << validWordCount << " words" << endl;
return 0;
}
|
Java
import java.util.*;
public class ValidWordsCount {
public static boolean isValidWord(String word) {
if (word.isEmpty()) {
return false ;
}
if (!Character.isLetter(word.charAt( 0 ))) {
return false ;
}
int hyphenCount = 0 ;
for ( int i = 1 ; i < word.length(); i++) {
if (word.charAt(i) == '-' ) {
hyphenCount++;
if (hyphenCount > 1 || i == 1 || i == word.length() - 1 || !Character.isLetter(word.charAt(i - 1 )) || !Character.isLetter(word.charAt(i + 1 ))) {
return false ;
}
} else if (!Character.isLowerCase(word.charAt(i))) {
return false ;
}
}
return true ;
}
public static int countValidWords(String sentence) {
int count = 0 ;
String word = "" ;
for ( int i = 0 ; i < sentence.length(); i++) {
if (Character.isWhitespace(sentence.charAt(i))) {
if (isValidWord(word)) {
count++;
}
word = "" ;
} else {
word += sentence.charAt(i);
}
}
if (isValidWord(word)) {
count++;
}
return count;
}
public static void main(String[] args) {
String sentence = "i Love- Geeks-Forgeeks!" ;
int validWordCount = countValidWords(sentence);
System.out.println(validWordCount + " words" );
}
}
|
Time Complexity: O(N) where N is the of length of string.
Auxiliary Space: O(1) for constant time taken