Encuentra el último carácter que no se repite en la string

Dada una string str , la tarea es encontrar el último carácter que no se repite en ella. 
Por ejemplo, si la string de entrada es «GeeksForGeeks» , la salida debería ser ‘r’ y si la string de entrada es «GeeksQuiz» , la salida debería ser ‘z’ . si no hay ningún carácter que no se repita, imprima -1 .
Ejemplos: 
 

Entrada: str = «GeeksForGeeks» 
Salida:
‘r’ es el primer carácter desde el final que tiene frecuencia 1.
Entrada: str = «aabbcc» 
Salida: -1 
Todos los caracteres de la string dada tienen frecuencias mayores que 1. 
 

Enfoque: cree una array de frecuencia que almacenará la frecuencia de cada uno de los caracteres de la string dada. Una vez que se hayan actualizado las frecuencias, comience a recorrer la string desde el final carácter por carácter y para cada carácter, si la frecuencia del carácter actual es 1, entonces este es el último carácter que no se repite. Si todos los caracteres tienen una frecuencia mayor que 1, imprima -1.
A continuación se muestra la implementación del enfoque anterior:
 

C++

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Maximum distinct characters possible
const int MAX = 256;
 
// Function to return the last non-repeating character
static string lastNonRepeating(string str, int n)
{
 
    // To store the frequency of each of
    // the character of the given string
    int freq[MAX] = {0};
 
    // Update the frequencies
    for (int i = 0; i < n; i++)
        freq[str.at(i)]++;
     
 
    // Starting from the last character
    for (int i = n - 1; i >= 0; i--)
    {
 
        // Current character
        char ch = str.at(i);
 
        // If frequency of the current character is 1
        // then return the character
        if (freq[ch] == 1)
        {
            string res;
            res+=ch;
            return res;
        }
    }
 
    // All the characters of the
    // string are repeating
    return "-1";
}
 
// Driver code
int main()
{
    string str = "GeeksForGeeks";
    int n = str.size();
    cout<< lastNonRepeating(str, n);
    return 0;
}
 
// This code has been contributed by 29AjayKumar

Java

// Java implementation of the approach
public class GFG {
 
    // Maximum distinct characters possible
    static final int MAX = 256;
 
    // Function to return the last non-repeating character
    static String lastNonRepeating(String str, int n)
    {
 
        // To store the frequency of each of
        // the character of the given string
        int freq[] = new int[MAX];
 
        // Update the frequencies
        for (int i = 0; i < n; i++)
            freq[str.charAt(i)]++;
 
        // Starting from the last character
        for (int i = n - 1; i >= 0; i--) {
 
            // Current character
            char ch = str.charAt(i);
 
            // If frequency of the current character is 1
            // then return the character
            if (freq[ch] == 1)
                return ("" + ch);
        }
 
        // All the characters of the
        // string are repeating
        return "-1";
    }
 
    // Driver code
    public static void main(String[] args)
    {
        String str = "GeeksForGeeks";
        int n = str.length();
        System.out.println(lastNonRepeating(str, n));
    }
}

Python3

# Python3 implementation of the approach
 
# Maximum distinct characters possible
MAX = 256;
 
# Function to return the last non-repeating character
def lastNonRepeating(string, n) :
 
    # To store the frequency of each of
    # the character of the given string
    freq = [0]*MAX;
 
    # Update the frequencies
    for i in range(n) :
        freq[ord(string[i])] += 1;
 
    # Starting from the last character
    for i in range(n-1,-1,-1) :
 
        # Current character
        ch = string[i];
 
        # If frequency of the current character is 1
        # then return the character
        if (freq[ord(ch)] == 1) :
            return ("" + ch);
     
 
    # All the characters of the
    # string are repeating
    return "-1";
 
 
# Driver code
if __name__ == "__main__" :
     
    string = "GeeksForGeeks";
    n = len(string);
     
    print(lastNonRepeating(string, n));
 
# This code is contributed by AnkitRai01

C#

// C# implementation of the approach
using System;
     
class GFG
{
 
    // Maximum distinct characters possible
    static readonly int MAX = 256;
 
    // Function to return the last non-repeating character
    static String lastNonRepeating(String str, int n)
    {
 
        // To store the frequency of each of
        // the character of the given string
        int []freq = new int[MAX];
 
        // Update the frequencies
        for (int i = 0; i < n; i++)
            freq[str[i]]++;
 
        // Starting from the last character
        for (int i = n - 1; i >= 0; i--)
        {
 
            // Current character
            char ch = str[i];
 
            // If frequency of the current character is 1
            // then return the character
            if (freq[ch] == 1)
                return ("" + ch);
        }
 
        // All the characters of the
        // string are repeating
        return "-1";
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        String str = "GeeksForGeeks";
        int n = str.Length;
        Console.WriteLine(lastNonRepeating(str, n));
    }
}
 
/* This code contributed by PrinciRaj1992 */

Javascript

<script>
 
// JavaScript implementation of the approach
     
     // Maximum distinct characters possible
    let MAX = 256;
     
    // Function to return the last non-repeating character
    function lastNonRepeating(str,n)
    {
        // To store the frequency of each of
        // the character of the given string
        let freq = new Array(MAX);
          for(let i=0;i<MAX;i++)
        {
            freq[i]=0;
        }
        // Update the frequencies
        for (let i = 0; i < n; i++)
            freq[str[i].charCodeAt(0)]++;
   
        // Starting from the last character
        for (let i = n - 1; i >= 0; i--) {
   
            // Current character
            let ch = str[i];
   
            // If frequency of the current character is 1
            // then return the character
            if (freq[ch.charCodeAt(0)] == 1)
                return ("" + ch);
        }
   
        // All the characters of the
        // string are repeating
        return "-1";
    }
     
    // Driver code
    let str = "GeeksForGeeks";
    let n = str.length;
    document.write(lastNonRepeating(str, n));
 
 
// This code is contributed by rag2127
 
</script>
Producción: 

r

 

Publicación traducida automáticamente

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