Compruebe si la string dada es una palabra válida en inglés o no

Dada la string str , la tarea es verificar si esta string str consiste en palabras válidas en inglés o no.

Una string se conoce como una palabra válida en inglés si cumple con todos los criterios a continuación:

  • La string puede tener un carácter en mayúscula como primer carácter únicamente.
  • La string solo puede tener caracteres en minúsculas.
  • La string puede constar de un solo guión (‘-‘) rodeado de caracteres en ambos extremos.
  • La string no puede constar de ningún dígito.
  • Si hay algún signo de puntuación, debe ser uno solo y debe estar presente al final.

Imprime el número de palabras válidas en la string str.

Entrada: str = “¡Me encantan los geeks-forgeeks!”
Salida: 1 palabra
Explicación: 
palabra 1 = «i» no contiene el primer carácter en mayúscula, no es una palabra válida palabra
2 = «Amor-» El guión no está rodeado de caracteres en ambos extremos, no es una palabra válida
palabra 3 = » ¡Geeks-forgeeks! es una palabra valida

Entrada: str = “!este 1-s b8d!”
Salida: 0 palabras
Explicación:
palabra 1 = “!Este” signo de puntuación está al principio, no es palabra válida palabra
2 = “1-s” dígito como primer carácter, no es palabra válida
palabra 3 = “b8d!” el primer carácter no está en mayúsculas, no es una palabra válida              

Acercarse:

  • Inicialice la variable ans para llevar la cuenta del número de palabras válidas.
  • Recorra cada palabra presente en la oración.
  • Revisa cada letra de la palabra para ver si cumple con los criterios mencionados en el enunciado del problema.
  • Si alguno de los criterios no se cumple, devuelve falso.
  • Si todos los criterios son satisfechos por la palabra, entonces incremente el valor de la variable ans.
  • Imprime el valor de la variable ans.

A continuación se muestra el programa C++ del enfoque anterior:

C++

// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find valid words
bool ValidWords(string sentence)
{
    int hyphen = 0;
    int size = sentence.size();
    if (isupper(sentence[0])) {
        for (int i = 0; i < size; i++) {
            // Check for numbers
            if (isdigit(sentence[i]))
                return false;
            if (isupper(sentence[i]))
                return false;
 
            if (isalpha(sentence[i]))
                continue;
 
            if (sentence[i] == '-') {
                // Only 1 hyphen is allowed
                if (++hyphen > 1)
                    return false;
 
                // hyphen should be surrounded
                // by letters
                if (i - 1 < 0
                    || !isalpha(sentence[i - 1])
                    || i + 1 >= size
                    || !isalpha(sentence[i + 1]))
                    return false;
            }
 
            // Punctuation must be at the
            // end of the word
            else if (i != size - 1
                     && ispunct(sentence[i]))
                return false;
        }
    }
    else
        return true;
}
 
// Driver code
int main()
{
    string sentence = "i Love- Geeks-Forgeeks!";
 
    istringstream s(sentence);
    string word;
    int ans = 0;
 
    while (s >> word)
        if (ValidWords(word))
            ans++;
 
    // Display the result
    cout << ans << " words";
}

Java

/*package whatever //do not write package name here */
 
import java.io.*;
 
class GFG {
 
    // Function to find valid words
    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++) {
                // Check for numbers
                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) == '-') {
                    // Only 1 hyphen is allowed
                   hyphen = hyphen +1 ;
                    if (hyphen > 1)
                        return false;
 
                    // hyphen should be surrounded
                    // by letters
                    if (i - 1 < 0
                        || !Character.isAlphabetic(
                            sentence.charAt(i - 1))
                        || i + 1 >= size
                        || !Character.isAlphabetic(
                            sentence.charAt(i + 1)))
                        return false;
                }
 
                // Punctuation must be at the
                // end of the word
                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;
    }
 
    // Driver code
    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++;
            }
        }
 
        // Display the result
        System.out.print(ans + " words");
    }
}

Python3

# Python program to implement
# the above approach
 
# Function to find valid words
def ValidWords(sentence):
    hyphen = 0
    size = len(sentence)
    if (sentence[0] >= 'A' and sentence[0] <= 'Z'):
        for i in range(size):
           
            # Check for numbers
            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] == '-'):
               
                # Only 1 hyphen is allowed
                if (hyphen+1 > 1):
                    return False
                   
                # hyphen should be surrounded
                # by letters
                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
 
            # Punctuation must be at the
            # end of the word
            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
 
# Driver code
sentence = "i Love- Geeks-Forgeeks!"
 
word = sentence.split(' ')
ans = 0
 
for indx in word :
    if (ValidWords(indx)):
        ans += 1
 
# Display the result
print(f"{ans} words")
 
# This code is contributed by shinjanpatra

C#

/*package whatever //do not write package name here */
using System;
 
class GFG
{
 
  // Function to find valid words
  static bool ValidWords(String sentence)
  {
    int hyphen = 0;
    int size = sentence.Length;
    if (char.IsUpper(sentence[0]))
    {
      for (int i = 0; i < size; i++)
      {
         
        // Check for numbers
        if (char.IsDigit(sentence[i]))
          return false;
        if (char.IsUpper(sentence[i]))
          return false;
 
        if (char.IsLetter(sentence[i]))
          continue;
 
        if (sentence[i] == '-')
        {
           
          // Only 1 hyphen is allowed
          hyphen = hyphen + 1;
          if (hyphen > 1)
            return false;
 
          // hyphen should be surrounded
          // by letters
          if (i - 1 < 0
              || !char.IsLetter(sentence[i - 1])
              || i + 1 >= size
              || !char.IsLetter(sentence[i + 1]))
            return false;
        }
 
        // Punctuation must be at the
        // end of the word
        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;
  }
 
  // Driver code
  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++;
      }
    }
 
    // Display the result
    Console.Write(ans + " words");
  }
}
 
// This code is contributed by gfgking.

Javascript

<script>
    // JavaScript program to implement
    // the above approach
 
    // Function to find valid words
    const ValidWords = (sentence) => {
        let hyphen = 0;
        let size = sentence.length;
        if (sentence[0] >= 'A' && sentence[0] <= 'Z')
        {
            for (let i = 0; i < size; i++)
            {
                // Check for numbers
                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] == '-') {
                    // Only 1 hyphen is allowed
                    if (++hyphen > 1)
                        return false;
 
                    // hyphen should be surrounded
                    // by letters
                    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;
                }
 
                // Punctuation must be at the
                // end of the word
                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;
    }
 
    // Driver code
 
    let sentence = "i Love- Geeks-Forgeeks!";
 
    let word = sentence.split(' ');
    let ans = 0;
 
    for (let indx in word)
        if (ValidWords(word[indx]))
            ans++;
 
    // Display the result
    document.write(`${ans} words`);
 
    // This code is contributed by rakeshsahni
 
</script>
Producción

1 words

Complejidad temporal: O(N) 
Espacio auxiliar: O(N)

Publicación traducida automáticamente

Artículo escrito por manikajoshi500 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *