Máximo carácter que aparece en una string de entrada | Conjunto-2

Dada una string que contiene caracteres en minúsculas. La tarea es imprimir el carácter máximo que aparece en la string de entrada. Si 2 o más caracteres aparecen la misma cantidad de veces, escriba el carácter lexicográficamente (alfabéticamente) más bajo (el primero).
Ejemplos: 

Entrada: muestra de prueba 
Salida:
Explicación: e’t’, ‘e’ y ‘s’ aparecen 2 veces, pero ‘e’ es el carácter lexicográficamente más pequeño. 

Entrada: programa de muestra 
Salida: a

En el artículo anterior , si hay más de un carácter que aparece la cantidad máxima de veces, se devuelve cualquiera de los caracteres. En esta publicación, se devuelve el carácter lexicográficamente más pequeño de todos los caracteres.
Enfoque: Declare una array freq[26] que se usa como una tabla hash para almacenar las frecuencias de cada carácter en la string de entrada. Iterar en la string y aumentar el recuento de freq[s[i]] para cada carácter. Atraviese la array freq[] de izquierda a derecha y realice un seguimiento del carácter que tiene la frecuencia máxima hasta el momento. El valor en freq[i] representa la frecuencia del carácter (i + ‘a’).
A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ implementation to find
// the maximum occurring character in
// an input string which is lexicographically first
#include <bits/stdc++.h>
using namespace std;
 
// function to find the maximum occurring character in
// an input string which is lexicographically first
char getMaxOccurringChar(char str[])
{
    // freq[] used as hash table
    int freq[26] = { 0 };
 
    // to store maximum frequency
    int max = -1;
 
    // to store the maximum occurring character
    char result;
 
    // length of 'str'
    int len = strlen(str);
 
    // get frequency of each character of 'str'
    for (int i = 0; i < len; i++)
        freq[str[i] - 'a']++;
 
    // for each character, where character is obtained by
    // (i + 'a') check whether it is the maximum character
    // so far and accordingly update 'result'
    for (int i = 0; i < 26; i++)
        if (max < freq[i]) {
            max = freq[i];
            result = (char)(i + 'a');
        }
 
    // maximum occurring character
    return result;
}
 
// Driver Code
int main()
{
    char str[] = "sample program";
    cout << "Maximum occurring character = "
         << getMaxOccurringChar(str);
    return 0;
}

Java

// Java implementation to find
// the maximum occurring character in
// an input string which is lexicographically first
 
class GFG {
 
// function to find the maximum occurring character in
// an input string which is lexicographically first
    static char getMaxOccurringChar(char str[]) {
        // freq[] used as hash table
        int freq[] = new int[26];
 
        // to store maximum frequency
        int max = -1;
 
        // to store the maximum occurring character
        char result = 0;
 
        // length of 'str'
        int len = str.length;
 
        // get frequency of each character of 'str'
        for (int i = 0; i < len; i++) {
            if (str[i] != ' ') {
                freq[str[i] - 'a']++;
            }
        }
 
        // for each character, where character is obtained by
        // (i + 'a') check whether it is the maximum character
        // so far and accordingly update 'result'
        for (int i = 0; i < 26; i++) {
            if (max < freq[i]) {
                max = freq[i];
                result = (char) (i + 'a');
            }
        }
 
        // maximum occurring character
        return result;
    }
 
// Driver Code
    public static void main(String[] args) {
        char str[] = "sample program".toCharArray();
        System.out.println("Maximum occurring character = "
                + getMaxOccurringChar(str));
    }
}
 
// This code is contributed by 29AjayKumar

Python3

# Python 3 implementation to find the
# maximum occurring character in an input
# string which is lexicographically first
 
# function to find the maximum occurring
# character in an input string which is
# lexicographically first
def getMaxOccurringChar(str):
     
    # freq[] used as hash table
    freq = [0 for i in range(100)]
 
    # to store maximum frequency
    max = -1
 
    # to store the maximum occurring
    # character length of 'str'
    len__ = len(str)
 
    # get frequency of each character of 'str'
    for i in range(0, len__, 1):
        freq[ord(str[i]) - ord('a')] += 1
 
    # for each character, where character
    # is obtained by (i + 'a') check whether
    # it is the maximum character so far and
    # accordingly update 'result'
    for i in range(26):
        if (max < freq[i]):
            max = freq[i]
            result = chr(ord('a') + i)
 
    # maximum occurring character
    return result
 
# Driver Code
if __name__ == '__main__':
    str = "sample program"
    print("Maximum occurring character =",
                 getMaxOccurringChar(str))
     
# This code is contributed by
# Surendra_Gangwar

C#

// C# implementation to find
// the maximum occurring character in
// an input string which is lexicographically first
  
using System;
class GFG {
  
// function to find the maximum occurring character in
// an input string which is lexicographically first
    static char getMaxOccurringChar(string str) {
        // freq[] used as hash table
        int[] freq = new int[26];
  
        // to store maximum frequency
        int max = -1;
  
        // to store the maximum occurring character
        char result = (char)0;
  
        // length of 'str'
        int len = str.Length;
  
        // get frequency of each character of 'str'
        for (int i = 0; i < len; i++) {
            if (str[i] != ' ') {
                freq[str[i] - 'a']++;
            }
        }
  
        // for each character, where character is obtained by
        // (i + 'a') check whether it is the maximum character
        // so far and accordingly update 'result'
        for (int i = 0; i < 26; i++) {
            if (max < freq[i]) {
                max = freq[i];
                result = (char) (i + 'a');
            }
        }
  
        // maximum occurring character
        return result;
    }
  
// Driver Code
    public static void Main() {
        string str = "sample program";
        Console.WriteLine("Maximum occurring character = "
                + getMaxOccurringChar(str));
    }
}

Javascript

// C# implementation to find
// the maximum occurring character in
// an input string which is lexicographically first
  
using System;
class GFG {
  
// function to find the maximum occurring character in
// an input string which is lexicographically first
    static char getMaxOccurringChar(string str) {
        // freq[] used as hash table
        int[] freq = new int[26];
  
        // to store maximum frequency
        int max = -1;
  
        // to store the maximum occurring character
        char result = (char)0;
  
        // length of 'str'
        int len = str.Length;
  
        // get frequency of each character of 'str'
        for (int i = 0; i < len; i++) {
            if (str[i] != ' ') {
                freq[str[i] - 'a']++;
            }
        }
  
        // for each character, where character is obtained by
        // (i + 'a') check whether it is the maximum character
        // so far and accordingly update 'result'
        for (int i = 0; i < 26; i++) {
            if (max < freq[i]) {
                max = freq[i];
                result = (char) (i + 'a');
            }
        }
  
        // maximum occurring character
        return result;
    }
  
// Driver Code
    public static void Main() {
        string str = "sample program";
        Console.WriteLine("Maximum occurring character = "
                + getMaxOccurringChar(str));
    }
}
Producción

Maximum occurring character = a

Complejidad de tiempo: O(n), donde n es la longitud de la string de entrada dada. 
Espacio Auxiliar: O(1).
Fuente: Experiencia de entrevista con Saber | conjunto 2
 

Publicación traducida automáticamente

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