Dada una array de strings arr[] de tamaño N . Cada una de las strings contiene letras minúsculas o números en inglés solamente. La tarea es encontrar la frecuencia de strings alfabéticas y alfanuméricas en la array.
Nota: si alguna string tiene al menos un número, la string es una string alfanumérica.
Ejemplos:
Entrada: arr[] = {“abcd”, “mak87s”, “abcd”, “kakjdj”, “laojs7s6”}
Salida: 3 2
“abcd”: 2
“kakjdj”: 1
“mak87s”: 1
“laojs7s6”: 1
Explicación: De la entrada dada, las strings que solo tienen letras son
«abcd», «kakjdj» y las strings restantes contienen números. Así que 3 strings alfabéticas y dos alfanuméricas en total.
Estas dos strings tienen una frecuencia de 2 y 1 y las otras dos strings tienen una frecuencia de 1 cada una.Entrada: arr[] = {“defr3t”, “lsk4dk”, “njdcd”}
Salida: 1 2
“njdcd”: 1
“defr3t”: 1
“lsk4dk”: 1
Enfoque: El enfoque para resolver este problema se basa en la técnica hash . Siga los pasos que se mencionan a continuación para resolver el problema.
- Tome una función de mapa hash para contar la frecuencia
- Ahora itere a de 0 a N-1 y luego almacene.
- Ahora itere otro bucle for dentro del primer bucle for (bucle anidado) desde 0 hasta el tamaño de esa string.
- Ahora comprueba si cada elemento es un alfabeto o no.
- En caso afirmativo, incremente el recuento de strings alfabéticas y aumente la frecuencia de esa string en 1.
- De lo contrario, incremente el recuento de strings alfanuméricas y aumente la frecuencia de esa string en 1.
- Imprima el recuento total de strings alfanuméricas y alfabéticas y las frecuencias de cada string por separado.
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ code to implement the above approach #include <bits/stdc++.h> using namespace std; // Function to find frequency void find_freq(string v[], int n) { // Take an hash map function // to count frequency map<string, int> mp1, mp2; int count1 = 0, count2 = 0; bool flag; for (int i = 0; i < n; i++) { flag = true; for (int j = 0; j < v[i].size(); j++) { // Check whether the string has // numbers or not if (v[i][j] >= '0' && v[i][j] <= '9') { flag = false; break; } } // For alphabetic string if (flag) { count1++; mp1[v[i]]++; } // For alphanumeric string else { count2++; mp2[v[i]]++; } } cout << count1 << " " << count2 << endl; // Print the frequencies of // alphabetic strings for (auto it : mp1) { cout << it.first << ": " << it.second << endl; ; } // Print the frequencies of // alphanumeric strings for (auto it : mp2) { cout << it.first << ": " << it.second << endl; ; } } // Drive code int main() { int N = 5; string arr[] = { "abcd", "mak87s", "abcd", "kakjdj", "laojs7s6" }; // Function call find_freq(arr, N); return 0; }
Java
// Java code for the above approach import java.util.*; class GFG { // Function to find frequency static void find_freq(String v[], int n) { // Take an hash map function // to count frequency Map<String, Integer> mp1 = new HashMap<String, Integer>(); Map<String, Integer> mp2 = new HashMap<String, Integer>(); int count1 = 0, count2 = 0; Boolean flag; for (int i = 0; i < n; i++) { flag = true; for (int j = 0; j < v[i].length(); j++) { // Check whether the string has // numbers or not if (v[i].charAt(j) >= '0' && v[i].charAt(j) <= '9') { flag = false; break; } } // For alphabetic string if (flag) { count1++; if (mp1.containsKey(v[i])) { mp1.put(v[i], mp1.get(v[i]) + 1); } else { mp1.put(v[i], 1); } } // For alphanumeric string else { count2++; if (mp2.containsKey(v[i])) { mp2.put(v[i], mp2.get(v[i]) + 1); } else { mp2.put(v[i], 1); } } } System.out.println(count1 + " " + count2); // Print the frequencies of // alphabetic strings for (Map.Entry<String, Integer> entry : mp1.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } // Print the frequencies of // alphanumeric strings for (Map.Entry<String, Integer> entry : mp2.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } // Drive code public static void main (String[] args) { int N = 5; String arr[] = { "abcd", "mak87s", "abcd", "kakjdj", "laojs7s6" }; // Function call find_freq(arr, N); } } // This code is contributed by hrithikgarg03188.
Python3
# Python code to implement the above approach # Function to find frequency def find_freq(v, n): # Take an hash map function # to count frequency mp1 = {} mp2 = {} count1 = 0 count2 = 0 flag = False for i in range(n): flag = True for j in range(len(v[i])): # Check whether the string has # numbers or not if(v[i][j] >= '0' and v[i][j] <= '9'): flag = False break # For alphabetic string if (flag): count1 = count1+1 if v[i] in mp1: mp1[v[i]] = mp1[v[i]]+1 else : mp1[v[i]] = 1 # For alphanumeric string else : count2 = count2+1 if v[i] in mp1: mp2[v[i]] = mp2[v[i]]+1 else : mp2[v[i]] = 1 print(f"{count1} {count2}") # Print the frequencies of # alphabetic strings for key,value in mp1.items(): print(f"{key} : {value}") # Print the frequencies of # alphanumeric strings for key,value in mp2.items(): print(f"{key} : {value}") # Driver code N = 5 arr = [ "abcd", "mak87s", "abcd", "kakjdj", "laojs7s6" ]; # Function call find_freq(arr, N); # This code is contributed by shinjanpatra.
C#
// C# program to implement above approach using System; using System.Collections; using System.Collections.Generic; class GFG { // Function to find frequency static void find_freq(String[] v, int n) { // Take an hash map function // to count frequency SortedDictionary<String, int> mp1 = new SortedDictionary<String, int>(); SortedDictionary<String, int> mp2 = new SortedDictionary<String, int>(); int count1 = 0, count2 = 0; bool flag; for (int i = 0; i < n; i++) { flag = true; for (int j = 0 ; j < v[i].Length ; j++) { // Check whether the string has // numbers or not if (v[i][j] >= '0' && v[i][j] <= '9') { flag = false; break; } } // For alphabetic string if (flag) { count1++; if (mp1.ContainsKey(v[i])) { mp1[v[i]] += 1; } else { mp1.Add(v[i], 1); } } // For alphanumeric string else { count2++; if (mp2.ContainsKey(v[i])) { mp2[v[i]] += 1; } else { mp2.Add(v[i], 1); } } } Console.WriteLine(count1 + " " + count2); // Print the frequencies of // alphabetic strings foreach (KeyValuePair<String, int> entry in mp1) { Console.WriteLine(entry.Key + ": " + entry.Value); } // Print the frequencies of // alphanumeric strings foreach (KeyValuePair<String, int> entry in mp2) { Console.WriteLine(entry.Key + ": " + entry.Value); } } // Driver code public static void Main(string[] args) { int N = 5; String[] arr = new String[]{ "abcd", "mak87s", "abcd", "kakjdj", "laojs7s6" }; // Function call find_freq(arr, N); } } // This code is contributed by subhamgoyal2014.
Javascript
<script> // JavaScript code to implement the above approach // Function to find frequency const find_freq = (v, n) => // Take an hash map function // to count frequency let mp1 = {}, mp2 = {}; let count1 = 0, count2 = 0; let flag = false; for (let i = 0; i < n; i++) { flag = true; for (let j = 0; j < v[i].length; j++) { // Check whether the string has // numbers or not if (v[i][j] >= '0' && v[i][j] <= '9') { flag = false; break; } } // For alphabetic string if (flag) { count1++; if (v[i] in mp1) mp1[v[i]] += 1 else mp1[v[i]] = 1; } // For alphanumeric string else { count2++; if (v[i] in mp2) mp2[v[i]] += 1; else mp2[v[i]] = 1; } } document.write(`${count1} ${count2}<br/>`); // Print the frequencies of // alphabetic strings for (let it in mp1) { document.write(`${it}: ${mp1[it]}<br/>`); } // Print the frequencies of // alphanumeric strings for (let it in mp2) { document.write(`${it}: ${mp2[it]}<br/>`); } } // Drive code let N = 5; let arr = ["abcd", "mak87s", "abcd", "kakjdj", "laojs7s6"]; // Function call find_freq(arr, N); // This code is contributed by rakeshsahni </script>
3 2 abcd: 2 kakjdj: 1 laojs7s6: 1 mak87s: 1
Complejidad de tiempo: O(N * M) donde M es la longitud máxima de una string
Espacio auxiliar: O(N)
Publicación traducida automáticamente
Artículo escrito por bunny09262002 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA