Cuente dominios únicos de una lista de correos electrónicos dada

Dada una array arr[] que contiene N direcciones de correo electrónico con diferentes dominios, la tarea es encontrar los dominios únicos y sus frecuencias de la lista de correos electrónicos.

Nota:  La aparición del dominio debe imprimirse en el orden lexicográfico de los nombres de dominio.

Ejemplos:

Entrada: arr[] = { “rupesh@gmail.com”, “akole@yahoo.com”, “rupesh.21910879@viit.ac.in”,  
                         “facultad.apellido@viit.ac.in”, “Shyam@ gmail.com”, “examcell@viit.ac.in”} 
Salida: gmail.com 2 
              viit.ac.in 3
              yahoo.com 1
Explicación:  Aquí los dominios únicos en orden lexicográfico de la lista de correos electrónicos son: 
gmail.com , viit.ac.in, yahoo.com.
Y su respectiva frecuencia en la lista es 2, 3 y 1.

Entrada: arr[] = {“geeks@geeksforgeeks.org”, “google@gmail.com”}
Salida: geeksforgeeks.org 1
            gmail.com 1

 

Planteamiento: La solución al problema se basa en la siguiente idea:

Los dominios de un correo electrónico se mencionan después del símbolo ‘@’. Entonces, encuentre todos los dominios y almacene sus frecuencias.

Siga los pasos mencionados a continuación para implementar la idea:

  • Inicialice un mapa para almacenar las frecuencias de cada dominio único en el orden lexicográfico de los nombres de dominio. 
  • Transverse cada una de las entradas de correo electrónico:
    • Para cada entrada, busque el índice (por ejemplo, idx ) del símbolo ‘@’.
    • La substring que comienza desde idx+1 hasta el final de la string es el nombre de dominio.
    • Guarde este dominio en el mapa y aumente su frecuencia en 1 .
  • Repita el mapa desde el principio (ya que las claves ya están ordenadas) e imprima los nombres de dominio y sus frecuencias.  

A continuación se muestra la implementación del enfoque anterior.

C++

// C++ code to implement the approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the unique domains
// and their frequencies
vector<pair<string, int> > finddomains(
    vector<string> input)
{
    // Map to store unique domains
    // and their frequency
    map<string, int> domainFre;
    vector<pair<string, int> > ans;
 
    // Loop to find the unique domains
    for (int i = 0; i < input.size(); i++) {
 
        // Find the index of '@' symbol in string
        auto findindex = input[i].find('@');
 
        // Push the substring starting from
        // findindex + 1 till the end
        // and then increase its frequency by 1
        domainFre[input[i].substr(findindex + 1)]++;
    }
 
    // Store the key value pair into
    // vector and finally return it.
    for (auto it : domainFre)
        ans.push_back({ it.first, it.second });
 
    // Return the domains and their frequencies
    return ans;
}
 
// Driver code
int main()
{
    vector<string> input = {
        "rupesh@gmail.com", "akole@yahoo.com",
        "rupesh.21910879@viit.ac.in",
        "faculty.surname@viit.ac.in",
        "Shyam@gmail.com", "examcell@viit.ac.in"
    };
    vector<pair<string, int> > ans;
 
    // Function call
    ans = finddomains(input);
 
    // Print the unique domains and
    // their frequencies
    // in lexicographical order
    for (int i = 0; i < ans.size(); i++)
        cout << ans[i].first << " "
             << ans[i].second << endl;
    return 0;
}

Java

// Java code to implement the approach
import java.io.*;
import java.util.*;
 
class pair {
    String first;
    int second;
    pair(String first, int second)
    {
        this.first = first;
        this.second = second;
    }
}
 
class GFG {
    // Function to find the unique domains
    // and their frequencies
    public static ArrayList<pair>
        finddomains(String[] input)
    {
        // Map to store unique domains
        // and their frequency
        TreeMap<String, Integer> domainFre
            = new TreeMap<String, Integer>();
        ArrayList<pair> ans = new ArrayList<>();
 
        // Loop to find the unique domains
        for (int i = 0; i < input.length; i++) {
 
            // Find the index of '@' symbol in string
            int findindex = input[i].indexOf('@');
 
            // Push the substring starting from
            // findindex + 1 till the end
            // and then increase its frequency by 1
            String temp = input[i].substring(findindex + 1);
            if (domainFre.get(temp) != null) {
                domainFre.put(temp,
                              domainFre.get(temp) + 1);
            }
            else {
                domainFre.put(temp, 1);
            }
        }
 
        // Store the key value pair into
        // vector and finally return it.
        for (Map.Entry<String, Integer> it :
             domainFre.entrySet())
            ans.add(new pair(it.getKey(), it.getValue()));
 
        // Return the domains and their frequencies
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String input[] = { "rupesh@gmail.com",
                           "akole@yahoo.com",
                           "rupesh.21910879@viit.ac.in",
                           "faculty.surname@viit.ac.in",
                           "Shyam@gmail.com",
                           "examcell@viit.ac.in" };
 
        // Function call
        ArrayList<pair> ans = finddomains(input);
 
        // Print the unique domains and
        // their frequencies
        // in lexicographical order
        for (int i = 0; i < ans.size(); i++)
            System.out.println(ans.get(i).first + " "
                               + ans.get(i).second);
    }
}
 
// This code is contributed by Rohit Pradhan

Python3

# Python3 code to implement the approach
 
# function to find the unique domains
# and their frequencies
def finddomains(input_):
   
    # map to store unique domains
    # and their frequency
    domainFre = dict()
    ans = []
 
    # loop to find the unique domains
    for i in range(len(input_)):
        # find the index of '@' symbol in the string
        findindex = input_[i].index('@')
 
        # Push the substring starting from
        # findindex + 1 till the end
        # and then increase its frequency by 1
        if input_[i][findindex + 1::] in domainFre:
            domainFre[input_[i][findindex + 1::]] += 1
        else:
            domainFre[input_[i][findindex + 1::]] = 1
 
    # store the key value pair  into the
    # ans list and finally return it
    for it in domainFre:
        ans.append([it, domainFre[it]])
 
    # sorting the ans list
    ans.sort()
    return ans
 
 
# Driver Code
input_ = ["rupesh@gmail.com", "akole@yahoo.com",
          "rupesh.21910879@viit.ac.in",
          "faculty.surname@viit.ac.in",
          "Shyam@gmail.com", "examcell@viit.ac.in"]
ans = []
 
# Function call
ans = finddomains(input_)
 
# Print the unique domains and
# their frequencies
# in lexicographical order
for i in range(len(ans)):
    print(ans[i][0], ans[i][1])
     
     
# This code is contributed by phasing17

C#

// C# program to implement above approach
using System;
using System.Collections;
using System.Collections.Generic;
 
class GFG
{
 
  // Function to find the unique domains
  // and their frequencies
  public static List<pair> finddomains(String[] input)
  {
    // Map to store unique domains
    // and their frequency
    SortedDictionary<String, int> domainFre = new SortedDictionary<String, int>();
    List<pair> ans = new List<pair>();
 
    // Loop to find the unique domains
    for (int i = 0 ; i < input.Length ; i++) {
 
      // Find the index of '@' symbol in string
      int findindex = input[i].IndexOf('@');
 
      // Push the substring starting from
      // findindex + 1 till the end
      // and then increase its frequency by 1
      String temp = input[i].Substring(findindex + 1);
      if (domainFre.ContainsKey(temp)) {
        domainFre[temp]+=1;
      }
      else {
        domainFre.Add(temp, 1);
      }
    }
 
    // Store the key value pair into
    // vector and finally return it.
    foreach (KeyValuePair<String, int> it in domainFre)
      ans.Add(new pair(it.Key, it.Value));
 
    // Return the domains and their frequencies
    return ans;
  }
 
  // Driver Code
  public static void Main(string[] args){
 
    String[] input = new String[]{
      "rupesh@gmail.com",
      "akole@yahoo.com",
      "rupesh.21910879@viit.ac.in",
      "faculty.surname@viit.ac.in",
      "Shyam@gmail.com",
      "examcell@viit.ac.in"
      };
 
    // Function call
    List<pair> ans = finddomains(input);
 
    // Print the unique domains and
    // their frequencies
    // in lexicographical order
    for (int i = 0 ; i < ans.Count ; i++){
      Console.WriteLine(ans[i].first + " " + ans[i].second);
    }
 
  }
}
 
public class pair{
  public String first;
  public int second;
  public pair(String first, int second)
  {
    this.first = first;
    this.second = second;
  }
}
 
// This code is contributed by subhamgoyal2014.

Javascript

<script>
    // JavaScript code to implement the approach
 
    // Function to find the unique domains
    // and their frequencies
    const finddomains = (input) => {
     
        // Map to store unique domains
        // and their frequency
        let domainFre = {};
        let ans = [];
 
        // Loop to find the unique domains
        for (let i = 0; i < input.length; i++) {
 
            // Find the index of '@' symbol in string
            let findindex = input[i].indexOf('@');
 
            // Push the substring starting from
            // findindex + 1 till the end
            // and then increase its frequency by 1
            if (input[i].substring(findindex + 1) in domainFre)
                domainFre[input[i].substring(findindex + 1)]++;
            else domainFre[input[i].substring(findindex + 1)] = 1;
        }
 
        // Store the key value pair into
        // vector and finally return it.
        for (let it in domainFre)
            ans.push([it, domainFre[it]]);
 
        // Return the domains and their frequencies
 
        return ans.sort();
    }
 
    // Driver code
 
    let input = [
        "rupesh@gmail.com", "akole@yahoo.com",
        "rupesh.21910879@viit.ac.in",
        "faculty.surname@viit.ac.in",
        "Shyam@gmail.com", "examcell@viit.ac.in"
    ];
    let ans = [];
 
    // Function call
    ans = finddomains(input);
 
    // Print the unique domains and
    // their frequencies
    // in lexicographical order
    for (let i = 0; i < ans.length; i++)
        document.write(`${ans[i][0]} ${ans[i][1]}<br/>`);
 
// This code is contributed by rakeshsahni
 
</script>
Producción

gmail.com 2
viit.ac.in 3
yahoo.com 1

Complejidad de tiempo: O(N * M) donde M es el tamaño de string promedio
Espacio auxiliar: O(K) donde K es el número de dominios únicos

Publicación traducida automáticamente

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