Comprobar si una string es un lipograma pangramático

Para comprender qué es un lipograma pangramático, dividiremos este término en 2 términos, es decir, un pangrama y un lipograma.

Pangrama : Un pangrama u oración holoalfabética es una oración que usa cada letra de un alfabeto dado al menos una vez. El pangrama inglés más conocido es «El rápido zorro marrón salta sobre el perro perezoso».

Lipograma : un lipograma es una especie de escritura restringida o juego de palabras que consiste en escribir párrafos o trabajos más largos en los que se evita una letra o grupo de letras en particular, generalmente una vocal común y, con frecuencia, la E, la letra más común en el idioma inglés. 

Ejemplo: A. Ross Eckler Jr. cambió el original “Mary Had a Little Lamb” para excluir la letra ‘S’.  

Original:
Mary had a little lamb
Its fleece was white as snow
And everywhere that Mary went
The lamb was sure to go

He followed her to school one day
That was against the rule
It made the children laugh and play
To see the lamb in school

Lipogram (Without "S"):
Mary had a little lamb
With fleece a pale white hue
And everywhere that Mary went
The lamb kept her in view

To academe he went with her,
Illegal, and quite rare;
It made the children laugh and play
To view the lamb in there

Lipograma pangramático

Un lipograma pangramático es un texto que utiliza todas las letras del alfabeto excepto una. Por ejemplo, “El veloz zorro pardo saltó sobre el perro perezoso” omite la letra S, que el pangrama habitual incluye usando la palabra salta. 

Dada una string, nuestra tarea es verificar si esta string es un lipograma pangramático o no.  

La idea de hacer esto es que realizaremos un seguimiento de todas las letras que no se encuentran en la string.  

  • Si todas las letras del alfabeto están presentes, entonces es un pangrama.
  • Si solo se omite una letra, entonces es un lipograma pangramático; de lo contrario, puede ser solo un lipograma.

A continuación se muestra la implementación de la idea anterior:  

C++

// Javascript program to check if a string
// is Pangrammatic Lipogram
 
#include<bits/stdc++.h>
using namespace std;
 
// collection of letters
string alphabets = "abcdefghijklmnopqrstuvwxyz";
 
 
// function to check for a Pangrammatic Lipogram
void panLipogramChecker(string s)
{  
    // convert string to lowercase
    for(int i=0; i<s.length(); i++)
    {
        s[i] = tolower(s[i]);
    }
     
    // variable to keep count of all the letters
    // not found in the string
    int counter = 0 ;
     
    // traverses the string for every
    // letter of the alphabet
    for(int i=0 ; i<26 ; i++)
    {  
        int pos = s.find(alphabets[i]);
         
        // if character not found in string
        // then increment count
        if(pos<0 || pos>s.length())
            counter += 1;
    }
   
    if(counter == 0)
        cout<<"Pangram"<<endl;
    else if(counter >= 2)
        cout<<"Not a pangram but might a lipogram"<<endl;
    else
        cout<<"Pangrammatic Lipogram"<<endl;
}
 
// Driver program to test above function
int main()
{
    string str = "The quick brown fox jumped over the lazy dog";
    panLipogramChecker(str);
     
    str = "The quick brown fox jumps over the lazy dog";
    panLipogramChecker(str);
     
    str = "The quick brown fox jump over the lazy dog";
    panLipogramChecker(str);
}

Java

// Java program to check if a string
// is Pangrammatic Lipogram
import java.util.*;
 
class GFG
{
 
// collection of letters
static String alphabets = "abcdefghijklmnopqrstuvwxyz";
 
/*
    Category             No of letters unmatched
    Pangram                     0
    Lipogram                 >1
    Pangrammatic Lipogram     1
*/
 
// function to check for a Pangrammatic Lipogram
static void panLipogramChecker(char []s)
{
    // convert string to lowercase
    for(int i = 0; i < s.length; i++)
    {
        s[i] = Character.toLowerCase(s[i]);
    }
     
    // variable to keep count of all the letters
    // not found in the string
    int counter = 0 ;
     
    // traverses the string for every
    // letter of the alphabet
    for(int i = 0 ; i < 26 ; i++)
    {
        int pos = find(s, alphabets.charAt(i));
         
        // if character not found in string
        // then increment count
        if(pos<0 || pos > s.length)
            counter += 1;
    }
     
    if(counter == 0)
        System.out.println("Pangram");
    else if(counter >= 2)
        System.out.println("Not a pangram but might a lipogram");
    else
        System.out.println("Pangrammatic Lipogram");
}
 
static int find(char[]arr, char c)
{
    for(int i = 0; i < arr.length; i++)
    {
        if(c == arr[i])
            return 1;
    }
    return -1;
}
 
// Driver program to test above function
public static void main(String []args)
{
    char []str = "The quick brown fox jumped over the lazy dog".toCharArray();
    panLipogramChecker(str);
     
    str = "The quick brown fox jumps over the lazy dog".toCharArray();
    panLipogramChecker(str);
     
    str = "The quick brown fox jump over the lazy dog".toCharArray();
    panLipogramChecker(str);
}
}
 
// This code is contributed by Rajput-Ji

Python3

# Python program to check if a string
# is Pangrammatic Lipogram
 
# collection of letters
alphabets = 'abcdefghijklmnopqrstuvwxyz'
 
'''
Category                No of letters unmatched
Pangram                     0
Lipogram                    >1
Pangrammatic Lipogram       1
'''
 
# function to check for a Pangrammatic Lipogram
def panLipogramChecker(s):
    s.lower()
     
    # variable to keep count of all the letters
    # not found in the string
    counter = 0
     
    # traverses the string for every
    # letter of the alphabet
    for ch in alphabets:
        # character not found in string then increment count
        if(s.find(ch) < 0):
            counter += 1
 
    if(counter == 0):
        result = "Pangram"
    else if(counter == 1):
        result = "Pangrammatic Lipogram"
    else:
        result = "Not a pangram but might a lipogram"
 
    return result
 
# Driver program to test above function
def main():
    print(panLipogramChecker("The quick brown fox \
                            jumped over the lazy dog"))
     
    print(panLipogramChecker("The quick brown fox \
                              jumps over the lazy dog"))
 
    print(panLipogramChecker("The quick brown fox jump\
                                     over the lazy dog"))
     
 
if __name__ == '__main__':
    main()

C#

// C# program to check if a string
// is Pangrammatic Lipogram
using System;
     
class GFG
{
 
// collection of letters
static String alphabets = "abcdefghijklmnopqrstuvwxyz";
 
/*
    Category             No of letters unmatched
    Pangram                     0
    Lipogram                 >1
    Pangrammatic Lipogram     1
*/
 
// function to check for a Pangrammatic Lipogram
static void panLipogramChecker(char []s)
{
    // convert string to lowercase
    for(int i = 0; i < s.Length; i++)
    {
        s[i] = char.ToLower(s[i]);
    }
     
    // variable to keep count of all the letters
    // not found in the string
    int counter = 0 ;
     
    // traverses the string for every
    // letter of the alphabet
    for(int i = 0 ; i < 26 ; i++)
    {
        int pos = find(s, alphabets[i]);
         
        // if character not found in string
        // then increment count
        if(pos<0 || pos > s.Length)
            counter += 1;
    }
     
    if(counter == 0)
        Console.WriteLine("Pangram");
    else if(counter >= 2)
        Console.WriteLine("Not a pangram but might a lipogram");
    else
        Console.WriteLine("Pangrammatic Lipogram");
}
 
static int find(char[]arr, char c)
{
    for(int i = 0; i < arr.Length; i++)
    {
        if(c == arr[i])
            return 1;
    }
    return -1;
}
 
// Driver program to test above function
public static void Main(String []args)
{
    char []str = "The quick brown fox jumped over the lazy dog".
                                                  ToCharArray();
    panLipogramChecker(str);
     
    str = "The quick brown fox jumps over the lazy dog".   
                                          ToCharArray();
    panLipogramChecker(str);
     
    str = "The quick brown fox jump over the lazy dog".
                                        ToCharArray();
    panLipogramChecker(str);
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// Javascript program to check if a string 
// is Pangrammatic Lipogram
let alphabets = "abcdefghijklmnopqrstuvwxyz";
 
   
/*
    Category             No of letters unmatched
    Pangram                     0
    Lipogram                 >1
    Pangrammatic Lipogram     1
*/
 
// Function to check for a Pangrammatic Lipogram
function panLipogramChecker(s)
{  
     
    // Convert string to lowercase
    for(let i = 0; i < s.length; i++)
    {
        s[i] = s[i].toLowerCase;
    }
     
    // Variable to keep count of all the letters
    // not found in the string
    let counter = 0;
     
    // Traverses the string for every
    // letter of the alphabet
    for(let i = 0; i < 26; i++)
    {
        let pos = s.search(alphabets[i]);
         
        // If character not found in string
        // then increment count
        if (pos < 0 || pos > s.length)
            counter += 1;
    }
   
    if (counter == 0)
        document.write("Pangram");
    else if (counter >= 2)
        document.write("Not a pangram but " +
                       "might a lipogram");
    else
        document.write("Pangrammatic Lipogram");
}
 
// Driver code
let str = "The quick brown fox jumped " +
          "over the lazy dog";
panLipogramChecker(str);
document.write("<br>");
 
str = "The quick brown fox jumps over " +
      "the lazy dog";
panLipogramChecker(str);
document.write("<br>");
 
str = "The quick brown fox jump " +
      "over the lazy dog";
panLipogramChecker(str);
 
// This code is contributed by annianni
 
</script>
Producción

Pangrammatic Lipogram
Pangram
Pangrammatic Lipogram

Complejidad de tiempo: O (26 * N) , aquí N es el número de caracteres en la string que se verificará y 26 representa el número total de alfabetos.
Espacio Auxiliar: O(1)

Enfoque eficiente: un enfoque eficiente será, en lugar de iterar a través de todas las letras del alfabeto, podemos mantener una array o mapa hash para almacenar el recuento de ocurrencias de cada letra del alfabeto en la string de entrada. Inicialmente, el recuento de todas las letras se inicializará a cero. Comenzaremos a recorrer la string e incrementaremos el conteo de caracteres. Una vez que hayamos completado el recorrido de la string, iteraremos sobre el mapa o la array hash para buscar cuántos caracteres cuentan como cero. 

Gracias a Ravi Teja Gannavarapu por sugerir este enfoque .

A continuación se muestra la implementación de la idea anterior.  

C++

// C++ program to check for a Pangrammatic
// Lipogram O(n) approach
 
/*
Category                No of letters unmatched
Pangram                     0
Lipogram                    >1
Pangrammatic Lipogram       1
*/
 
#include <bits/stdc++.h>
using namespace std;
 
// function to check for Pangrammatic Lipogram
void panLipogramChecker(string s)
{
 
    // using map to keep count of the
    // occurrence of each letter
    unordered_map<char, int> mp;
 
    for (char c = 'a'; c <= 'z'; c++) {
        mp = 0;
    }
 
    transform(s.begin(), s.end(), s.begin(), ::tolower);
 
    int i, n = s.length();
    for (i = 0; i <= n - 1; i++) {
        if (isalpha(s[i])) {
 
            // increment count of characters in dictionary
            mp[s[i]]++;
        }
    }
    int count_zero = 0;
 
    for (auto it : mp) {
        if (it.second == 0) {
            count_zero++;
        }
    }
    if (count_zero > 1) {
        cout << "Not a pangram, but might be a lipogram.\n";
    }
    else if (count_zero == 1) {
        cout << "Pangrammatic Lipogram.\n";
    }
    else if (count_zero < 1) {
        cout << "Pangram.\n";
    }
}
 
// Driver program to test above function
int main()
{
 
    panLipogramChecker("The quick brown fox \
                        jumped over the lazy dog");
    panLipogramChecker("The quick brown fox \
                        jumps over the lazy dog");
    panLipogramChecker("The quick brown fox \
                        jum over the lazy dog");
    return 0;
}
 
// This code is contributed by rajsanghavi9.

Java

// Java program to check for a Pangrammatic
// Lipogram O(n) approach
 
/*
Category                No of letters unmatched
Pangram                     0
Lipogram                    >1
Pangrammatic Lipogram       1
*/
 
import java.util.*;
 
class GFG {
 
    // function to check for Pangrammatic Lipogram
    static void panLipogramChecker(String s)
    {
 
        // using map to keep count of the
        // occurrence of each letter
        HashMap<Character, Integer> mp = new HashMap<>();
 
        for (char c = 'a'; c <= 'z'; c++) {
            mp.put(c, 0);
        }
 
        s = s.toLowerCase();
 
        int i, n = s.length();
        for (i = 0; i <= n - 1; i++) {
            if (Character.isAlphabetic(s.charAt(i))) {
 
                // increment count of characters in
                // dictionary
                mp.put(s.charAt(i),
                       mp.get(s.charAt(i)) + 1);
            }
        }
        int count_zero = 0;
 
        // Getting an iterator
        Iterator hmIterator = mp.entrySet().iterator();
 
        while (hmIterator.hasNext()) {
            Map.Entry mapElement
                = (Map.Entry)hmIterator.next();
            int marks = ((int)mapElement.getValue());
 
            if (marks == 0)
                count_zero++;
        }
        if (count_zero > 1) {
            System.out.println(
                "Not a pangram, but might be a lipogram.");
        }
        else if (count_zero == 1) {
            System.out.println("Pangrammatic Lipogram.");
        }
        else if (count_zero < 1) {
            System.out.println("Pangram.");
        }
    }
 
    public static void main(String[] args)
    {
        panLipogramChecker(
            "The quick brown fox jumped over the lazy dog");
        panLipogramChecker(
            "The quick brown fox jumps over the lazy dog");
        panLipogramChecker(
            "The quick brown fox jum over the lazy dog");
    }
}
 
// This code is contributed by rajsanghavi9.

Python3

# Python program to check for a Pangrammatic
# Lipogram O(n) approach
 
'''
Category                No of letters unmatched
Pangram                     0
Lipogram                    >1
Pangrammatic Lipogram       1
'''
 
# function to check for Pangrammatic Lipogram
 
 
def panLipogramChecker(s):
 
    # dictionary to keep count of the
    # occurrence of each letter
    counter = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0,
               'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0,
               'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0,
               'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0,
               'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0,
               'z': 0}
 
    s = s.lower()
 
    # increment count of characters in dictionary
    for i in s:
        if (i.isalpha()):
            counter[i] += 1
 
    # returns a list containing the values of all
    # the keys in h=the dictionary
    b = list(counter.values())
 
    if (b.count(0) > 1):
        print("Not a pangram, but might be a lipogram.")
    else if (b.count(0) == 1):
        print("Pangrammatic Lipogram.")
    else if (b.count(0) < 1):
        print("Pangram.")
 
 
# Driver program to test above function
def main():
    panLipogramChecker("The quick brown fox \
                        jumped over the lazy dog")
    panLipogramChecker("The quick brown fox \
                        jumps over the lazy dog")
    panLipogramChecker("The quick brown fox \
                        jum over the lazy dog")
 
 
if __name__ == '__main__':
    main()

C#

// C# program to check for a Pangrammatic
// Lipogram O(n) approach
 
/*
    Category             No of letters unmatched
    Pangram                     0
    Lipogram                   >1
    Pangrammatic Lipogram       1
*/
 
using System;
using System.Collections.Generic;
      
class GFG
{
 
    // function to check for a Pangrammatic Lipogram
    static void panLipogramChecker(string s)
    {
        // using map to keep count of the
        // occurrence of each letter
        Dictionary<char, int> mp = new Dictionary<char, int>();
  
        for (char c = 'a'; c <= 'z'; c++)
        {
            mp.Add(c, 0);
        }
  
        s = s.ToLower();
  
        int i, n = s.Length;
        for (i = 0; i <= n - 1; i++)
        {
            if (Char.IsLetter(s[i]))
            {
  
                // increment count of characters in
                // dictionary
                mp[s[i]] = mp[s[i]] + 1;
            }
        }
        int count_zero = 0, marks;
  
        // Getting an iterator
        foreach(KeyValuePair<char, int> entry in mp)
        {
            marks = (int) entry.Value;
  
            if (marks == 0)
                count_zero++;
        }
 
        if (count_zero > 1)
        {
            Console.WriteLine("Not a pangram, but might be a lipogram.");
        }
        else if (count_zero == 1)
        {
            Console.WriteLine("Pangrammatic Lipogram.");
        }
        else if (count_zero < 1)
        {
            Console.WriteLine("Pangram.");
        }
    }
 
    // Driver program to test above function
    public static void Main(String []args)
    {
        string str = "The quick brown fox jumped over the lazy dog";
        panLipogramChecker(str);
 
        str = "The quick brown fox jumps over the lazy dog";
        panLipogramChecker(str);
 
        str = "The quick brown fox jum over the lazy dog";
        panLipogramChecker(str);
    }
}
  
// This code is contributed by kothavvsaakash

Javascript

<script>
// JavaScript program to check for a Pangrammatic
// Lipogram O(n) approach
  
/*
Category                No of letters unmatched
Pangram                     0
Lipogram                    >1
Pangrammatic Lipogram       1
*/
 
// count number of occurrences of `n` in arr
const count = (arr , n) => arr.filter(x => x === n).length
 
// function to check for Pangrammatic Lipogram
const panLipogramChecker = (s) => {
    const counter = {'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0,
    'f': 0, 'g': 0, 'h': 0, 'i': 0, 'j': 0,
    'k': 0, 'l': 0, 'm': 0, 'n': 0, 'o': 0,
    'p': 0, 'q': 0, 'r': 0, 's': 0, 't': 0,
    'u': 0, 'v': 0, 'w': 0, 'x': 0, 'y': 0,
    'z': 0}
 
    s = s.toLowerCase()
 
    // Couting frequency of each character
    for(let i of s) {
        if(/^[a-z]+$/gi.test(i)) {
            counter[i] += 1
        }
    }
 
    const b = Object.values(counter)
 
    if(count(b , 0) > 1) {
        document.write("Not a pangram, but might be a lipogram.")
    }
    else if(count(b , 0) == 1) {
        document.write("Pangrammatic Lipogram.")
    } else {
        document.write("Pangram.")
    }
}
 
// Driver code
panLipogramChecker("The quick brown fox jumped over the lazy dog")
panLipogramChecker("The quick brown fox jumps over the lazy dog")
panLipogramChecker("The quick brown fox jum over the lazy dog")
 
// This code is contributed by kraanzu.
</script>
Producción

Pangrammatic Lipogram.
Pangram.
Not a pangram, but might be a lipogram.

Complejidad de tiempo: O(N), donde N es el número de caracteres en la string de entrada.
Espacio Auxiliar: O(N) , debido al mapa

Este artículo es una contribución de Palash Nigam . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks. 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 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 *