Carácter repetido máximo para cada índice en una string dada

Dada la string str que consta de alfabetos en minúsculas, la tarea es encontrar el máximo de caracteres repetidos obtenidos para cada carácter de la string. Si para cualquier índice, se ha producido más de un carácter un número máximo de veces, imprima el carácter que se haya producido más recientemente.

Ejemplos:

Entrada: str = “abbc”
Salida: 
a -> 1
b -> 1
b -> 2
b -> 2 
Explicación: 
str[0] = ‘a’. Por lo tanto, imprima a -> 1. 
str[1] = ‘b’. Ahora ‘a’ y ‘b’ tienen la misma frecuencia. Dado que ‘b’ es el carácter más reciente, imprima b -> 1. 
str[2] = ‘b’. Dado que ‘b’ es el carácter que más se repite, imprima b -> 2. 
str[3] = ‘c’. Dado que ‘b’ es el carácter que más se repite, imprima b -> 2.

Entrada: str = “htdddg”
Salida: h -> 1
t -> 1
d -> 1
d -> 2
d -> 3
d -> 3

Enfoque: siga los pasos que se indican a continuación para resolver el problema:

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

C++

// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to print the
// maximum repeating
// character at each index
// of the String
void findFreq(string str,
              int N)
{
  // Stores frequency of
  // each distinct character
  int freq[256];
   
  memset(freq, 0,
         sizeof(freq));
 
  // Stores frequency of
  // maximum repeating
  // character
  int max = 0;
 
  // Stores the character having
  // maximum frequency
  char charMax = '0';
 
  // Traverse the String
  for (int i = 0; i < N; i++)
  {
    // Stores current character
    char ch = str[i];
 
    // Update the frequency of str[i]
    freq[ch]++;
 
    // If frequency of current
    // character exceeds max
    if (freq[ch] >= max)
    {
      // Update max
      max = freq[ch];
 
      // Update charMax
      charMax = ch;
    }
 
    // Print the required output
    cout<< charMax << "->" <<
           max << endl;
  }
}
 
// Driver Code
int main()
{
  string str = "abbc";
 
  // Stores length of str
  int N = str.size();
 
  findFreq(str, N);
}
 
// This code is contributed by Rajput-Ji

Java

// Java program to implement
// the above approach
 
import java.util.*;
 
public class GFG {
 
    // Function to print the maximum repeating
    // character at each index of the string
    public static void findFreq(String str,
                                int N)
    {
 
        // Stores frequency of
        // each distinct character
        int[] freq = new int[256];
 
        // Stores frequency of maximum
        // repeating character
        int max = 0;
 
        // Stores the character having
        // maximum frequency
        char charMax = '0';
 
        // Traverse the string
        for (int i = 0; i < N; i++) {
 
            // Stores current character
            char ch = str.charAt(i);
 
            // Update the frequency of str[i]
            freq[ch]++;
 
            // If frequency of current
            // character exceeds max
            if (freq[ch] >= max) {
 
                // Update max
                max = freq[ch];
 
                // Update charMax
                charMax = ch;
            }
 
            // Print the required output
            System.out.println(
                charMax + " -> " + max);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String str = "abbc";
 
        // Stores length of str
        int N = str.length();
 
        findFreq(str, N);
    }
}

Python3

# Python3 program to implement
# the above approach
 
# Function to print the maximum repeating
# character at each index of the string
def findFreq(strr, N):
     
    # Stores frequency of
    # each distinct character
    freq = [0] * 256
 
    # Stores frequency of maximum
    # repeating character
    max = 0
 
    # Stores the character having
    # maximum frequency
    charMax = '0'
 
    # Traverse the string
    for i in range(N):
         
        # Stores current character
        ch = ord(strr[i])
 
        # Update the frequency of strr[i]
        freq[ch] += 1
 
        # If frequency of current
        # character exceeds max
        if (freq[ch] >= max):
 
            # Update max
            max = freq[ch]
 
            # Update charMax
            charMax = ch
 
        # Print the required output
        print(chr(charMax), "->", max)
 
# Driver Code
if __name__ == '__main__':
     
    strr = "abbc"
 
    # Stores length of strr
    N = len(strr)
 
    findFreq(strr, N)
 
# This code is contributed by mohit kumar 29

C#

// C# program to implement
// the above approach
using System;
class GFG{
 
// Function to print the maximum repeating
// character at each index of the string
public static void findFreq(String str,
                            int N)
{
  // Stores frequency of
  // each distinct character
  int[] freq = new int[256];
 
  // Stores frequency of maximum
  // repeating character
  int max = 0;
 
  // Stores the character having
  // maximum frequency
  char charMax = '0';
 
  // Traverse the string
  for (int i = 0; i < N; i++)
  {
    // Stores current character
    char ch = str[i];
 
    // Update the frequency of
    // str[i]
    freq[ch]++;
 
    // If frequency of current
    // character exceeds max
    if (freq[ch] >= max)
    {
      // Update max
      max = freq[ch];
 
      // Update charMax
      charMax = ch;
    }
 
    // Print the required output
    Console.WriteLine(charMax +
                      " -> " + max);
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  String str = "abbc";
 
  // Stores length of str
  int N = str.Length;
 
  findFreq(str, N);
}
}
 
// This code is contributed by shikhasingrajput

Javascript

<script>
 
// JavaScript Program to implement
// the above approach
 
// Function to print the
// maximum repeating
// character at each index
// of the String
function findFreq(str, N) {
    // Stores frequency of
    // each distinct character
    let freq = new Array(256).fill(0);
 
 
    // Stores frequency of
    // maximum repeating
    // character
    let max = 0;
 
    // Stores the character having
    // maximum frequency
    let charMax = '0';
 
    // Traverse the String
    for (let i = 0; i < N; i++) {
        // Stores current character
        let ch = str[i].charCodeAt(0);
 
        // Update the frequency of str[i]
        freq[ch]++;
 
        // If frequency of current
        // character exceeds max
        if (freq[ch] >= max) {
            // Update max
            max = freq[ch];
 
            // Update charMax
            charMax = ch;
        }
 
        // Print the required output
        document.write(String.fromCharCode(charMax) + "->" +
        max + "<br>");
    }
}
 
// Driver Code
 
let str = "abbc";
 
// Stores length of str
let N = str.length;
 
findFreq(str, N);
 
 
// This code is contributed by gfgking
 
</script>
Producción: 

a -> 1
b -> 1
b -> 2
b -> 2

 

Complejidad temporal : O(N)
Espacio auxiliar: O(1)

Publicación traducida automáticamente

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