Encuentra el número total de años distintos de una string

Dada una string que contiene las palabras y las fechas, la tarea es encontrar el número total de años distintos mencionados en esa string. 
Nota: Asumiendo que la fecha estará en formato ‘DD-MM-YYYY’. 

Ejemplos:  

Input:  str = "UN was established on 24-10-1945.
                India got freedom on 15-08-1947."
Output: 2
2 distinct years i.e. 1945 and 1947 have been referenced.

Input: str = "Soon after the world war 2 ended on 02-09-1945.
        The UN was established on 24-10-1945."
Output: 1
Only 1 Year, i.e 1945 has been referenced .

Acercarse: 
 

  1. Comience a atravesar la cuerda.
  2. Compruebe si el carácter actual es un dígito. Guárdelo en otra string, es decir, dateString.
  3. Verifique si el carácter actual es ‘-‘, luego elimine los caracteres almacenados en dateString.
  4. Compruebe si la longitud de dateString es igual a 4, entonces significa que es un año.
  5. Guarde ese año en un conjunto unordered_set.
  6. Devuelve el tamaño de unordered_set ya que contiene solo valores únicos.

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

C++

// C++ Program to find the total
// number of distinct years
#include <bits/stdc++.h>
using namespace std;
 
// function to find the total
// number of distinct years
int distinct_year(string str)
{
    string str2 = "";
 
    unordered_set<string> uniqueDates;
 
    for (int i = 0; i < str.length(); i++) {
 
        if (isdigit(str[i])) {
            str2.push_back(str[i]);
        }
 
        // if we found - then clear the str2
        else if (str[i] == '-') {
            str2.clear();
        }
 
        // if length of str2 becomes 4
        // then store it in a set
        else if (str2.length() == 4) {
            uniqueDates.insert(str2);
            str2.clear();
        }
         
        // else clear the string.
        else{
           str2.clear();
        }
    }
 
    // return the size of set
    return uniqueDates.size();
}
 
// Driver code
int main()
{
    string str = "UN was established on 24-10-1945."
                 "India got freedom on 15-08-1947.";
 
    cout << distinct_year(str);
 
    return 0;
}

Java

import java.util.HashSet;
import java.util.Set;
 
// Java Program to find the total
// number of distinct years
public class GFG {
 
// function to find the total
// number of distinct years
    static int distinct_year(String str) {
        String str2 = "";
 
        Set<String> uniqueDates = new HashSet<>();
 
        for (int i = 0; i < str.length(); i++) {
 
            if (Character.isDigit(str.charAt(i))) {
                str2 += (str.charAt(i));
            }
 
            // if we found - then clear the str2
            if (str.charAt(i) == '-') {
                str2 = "";
            }
 
            // if length of str2 becomes 4
            // then store it in a set
            if (str2.length() == 4) {
                uniqueDates.add(str2);
                str2 = "";
            }
        }
 
        // return the size of set
        return uniqueDates.size();
    }
 
// Driver code
    static public void main(String[] args) {
        String str = "UN was established on 24-10-1945."
                + "India got freedom on 15-08-1947.";
 
        System.out.println(distinct_year(str));
    }
}

Python3

# Python3 Program to find the total
# number of distinct years
 
# function to find the total
# number of distinct years
import re
def distinct_years(str):
    str2 = ""
 
    uniqueDates = set()
    pattern="[0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]"
    dates = re.findall(pattern,str)
    for item in dates:
        uniqueDates.add(item.split('-')[-1])
    # return the size of se
    return len(uniqueDates)
 
# Driver code
if __name__ == "__main__":
    str = "UN was established on 24-10-1945.\
           India got freedom on 15-08-1947."
 
    print(distinct_years(str))
 
# This code is contributed by
# sanjeev2552

C#

// C# Program to find the total
// number of distinct years
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // function to find the total
    // number of distinct years
    static int distinct_year(String str)
    {
        String str2 = "";
 
        HashSet<String> uniqueDates = new HashSet<String>();
 
        for (int i = 0; i < str.Length; i++)
        {
            if (char.IsDigit(str[i]))
            {
                str2 += (str[i]);
            }
 
            // if we found - then clear the str2
            if (str[i] == '-')
            {
                str2 = "";
            }
 
            // if length of str2 becomes 4
            // then store it in a set
            if (str2.Length == 4)
            {
                uniqueDates.Add(str2);
                str2 = "";
            }
        }
 
        // return the size of set
        return uniqueDates.Count;
    }
 
    // Driver code
    static public void Main(String[] args)
    {
        String str = "UN was established on 24-10-1945." +
                     "India got freedom on 15-08-1947.";
 
        Console.WriteLine(distinct_year(str));
    }
}
 
// This code is contributed by Princi Singh

Javascript

<script>
 
// Javascript Program to find the total
// number of distinct years
 
// function to find the total
// number of distinct years
function distinct_year(str)
{
    var str2 = "";
 
    var uniqueDates = new Set();
 
    for (var i = 0; i < str.length; i++) {
 
        if (parseInt(str[i])) {
            str2+=(str[i]);
        }
 
        // if we found - then clear the str2
        if (str[i] == '-') {
            str2 = "";
        }
 
        // if length of str2 becomes 4
        // then store it in a set
        if (str2.length == 4) {
            uniqueDates.add(str2);
            str2 = "";
        }
    }
 
    // return the size of set
    return uniqueDates.size;
}
 
// Driver code
var str = "UN was established on 24-10-1945." +
             "India got freedom on 15-08-1947.";
document.write( distinct_year(str));
 
</script>
Producción

2

Complejidad de tiempo: O(n)
 

Publicación traducida automáticamente

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