Máximo carácter repetido consecutivo en string

Dada una string, la tarea es encontrar el máximo de caracteres repetidos consecutivos en una string.
Nota: No necesitamos considerar el conteo total, sino el conteo de repeticiones que aparece en un lugar.
Ejemplos: 
 

Input : str = "geeekk"
Output : e

Input : str = "aaaabbcbbb"
Output : a

La solución simple a este problema es usar dos bucles for. El ciclo externo considera el carácter actual, el ciclo interno cuenta las ocurrencias del carácter actual. Si el conteo supera el conteo máximo actual, actualizamos el resultado. 
 

C++

// C++ program to find the maximum consecutive
// repeating character in given string
#include<bits/stdc++.h>
using namespace std;
 
// function to find out the maximum repeating
// character in given string
char maxRepeating(string str)
{
    int len = str.length();
    int count = 0;
 
    // Find the maximum repeating character
    // starting from str[i]
    char res = str[0];
    for (int i=0; i<len; i++)
    {
        int cur_count = 1;
        for (int j=i+1; j<len; j++)
        {
            if (str[i] != str[j])
                break;
            cur_count++;
        }
 
        // Update result if required
        if (cur_count > count)
        {
            count = cur_count;
            res = str[i];
        }
    }
    return res;
}
 
// Driver code
int main()
{
 
    string str = "aaaabbaaccde";
    cout << maxRepeating(str);
    return 0;
}

Java

// Java program to find the maximum consecutive
// repeating character in given string
public class GFG {
     
    // function to find out the maximum repeating
    // character in given string
    static char maxRepeating(String str)
    {
        int len = str.length();
        int count = 0;
 
        // Find the maximum repeating character
        // starting from str[i]
        char res = str.charAt(0);
        for (int i=0; i<len; i++)
        {
            int cur_count = 1;
            for (int j=i+1; j<len; j++)
            {
                if (str.charAt(i) != str.charAt(j))
                    break;
                cur_count++;
            }
 
            // Update result if required
            if (cur_count > count)
            {
                count = cur_count;
                res = str.charAt(i);
            }
        }
        return res;
    }
 
    // Driver code
    public static void main(String args[])
    {
 
        String str = "aaaabbaaccde";
        System.out.println(maxRepeating(str));
    }
}
// This code is contributed by Sumit Ghosh

Python 3

# Python 3 program to find the
# maximum consecutive repeating
# character in given string
 
# function to find out the maximum
# repeating character in given string
def maxRepeating(str):
 
    l = len(str)
    count = 0
 
    # Find the maximum repeating
    # character starting from str[i]
    res = str[0]
    for i in range(l):
         
        cur_count = 1
        for j in range(i + 1, l):
     
            if (str[i] != str[j]):
                break
            cur_count += 1
 
        # Update result if required
        if cur_count > count :
            count = cur_count
            res = str[i]
    return res
 
# Driver code
if __name__ == "__main__":
 
    str = "aaaabbaaccde"
    print(maxRepeating(str))
 
# This code is contributed
# by ChitraNayal

C#

// C# program to find the maximum
// consecutive repeating character
// in given string
using System;
 
class GFG
{
 
// function to find out the maximum
// repeating character in given string
static char maxRepeating(string str)
{
    int len = str.Length;
    int count = 0;
    char res = str[0];
     
    // Find the maximum repeating
    // character starting from str[i]
    for (int i = 0; i < len; i++)
    {
        int cur_count = 1;
        for (int j = i + 1; j < len; j++)
        {
            if (str[i] != str[j])
                break;
            cur_count++;
        }
 
        // Update result if required
        if (cur_count > count)
        {
            count = cur_count;
            res = str[i];
        }
    }
    return res;
}
 
// Driver code
public static void Main()
{
    string str = "aaaabbaaccde";
    Console.Write(maxRepeating(str));
}
}
 
// This code is contributed
// by ChitraNayal

PHP

<?php
//PHP program to find the maximum consecutive
// repeating character in given string
 
// function to find out the maximum repeating
// character in given string
function  maxRepeating( $str)
{
     $len = strlen($str);
    $count = 0;
      
    // Find the maximum repeating character
    // starting from str[i]
     $res = $str[0];
    for ($i = 0; $i < $len; $i++)
    {
         $cur_count = 1;
        for ($j = $i+1; $j < $len; $j++)
        {
            if ($str[$i] != $str[$j])
                break;
            $cur_count++;
        }
 
        // Update result if required
        if ($cur_count > $count)
        {
            $count = $cur_count;
            $res = $str[$i];
        }
    }
    return $res;
}
 
// Driver code
    $str = "aaaabbaaccde";
    echo  maxRepeating($str);
 
// This code is contributed by ajit
?>

Javascript

<script>
 
// Javascript program to find the maximum consecutive
// repeating character in given string
     
    // function to find out the maximum repeating
    // character in given string
    function maxRepeating(str)
    {
        let len = str.length;
        let count = 0;
   
        // Find the maximum repeating character
        // starting from str[i]
        let res = str[0];
        for (let i=0; i<len; i++)
        {
            let cur_count = 1;
            for (let j=i+1; j<len; j++)
            {
                if (str[i] != str[j])
                    break;
                cur_count++;
            }
   
            // Update result if required
            if (cur_count > count)
            {
                count = cur_count;
                res = str[i];
            }
        }
        return res;
    }
     
    // Driver code
    let str = "aaaabbaaccde";
    document.write(maxRepeating(str));
     
    // This code is contributed by rag2127
 
</script>

Producción: 

a

Complejidad de tiempo: O(n^2) 
Complejidad de espacio: O(1)
Una solución eficiente es ejecutar solo un bucle. La idea es restablecer el conteo a 1 tan pronto como encontremos un carácter que no coincida con el anterior. 
 

C++

// C++ program to find the maximum consecutive
// repeating character in given string
#include<bits/stdc++.h>
using namespace std;
 
// Returns the maximum repeating character in a
// given string
char maxRepeating(string str)
{
    int n = str.length();
    int count = 0;
    char res = str[0];
    int cur_count = 1;
 
    // Traverse string except last character
    for (int i=0; i<n; i++)
    {
        // If current character matches with next
        if (i < n-1 && str[i] == str[i+1])
            cur_count++;
 
        // If doesn't match, update result
        // (if required) and reset count
        else
        {
            if (cur_count > count)
            {
                count = cur_count;
                res = str[i];
            }
            cur_count = 1;
        }
    }
 
    return res;
}
 
// Driver code
int main()
{
    string str = "aaaabbaaccde";
    cout << maxRepeating(str);
    return 0;
}

Java

// Java program to find the maximum consecutive
// repeating character in given string
class GFG {
     
    // function to find out the maximum repeating
    // character in given string
    static char maxRepeating(String str)
    {
        int n = str.length();
        int count = 0;
        char res = str.charAt(0);
        int cur_count = 1;
 
        // Traverse string except last character
        for (int i = 0; i < n; i++)
        {
            // If current character matches with next
            if (i < n - 1 && str.charAt(i) == str.charAt(i + 1))
                cur_count++;
 
            // If doesn't match, update result
            // (if required) and reset count
            else
            {
                if (cur_count > count)
                {
                    count = cur_count;
                    res = str.charAt(i);
                }
                cur_count = 1;
            }
        }
        return res;
    }
 
    // Driver code
    public static void main(String args[])
    {
        String str = "aaaabbaaccde";
        System.out.println(maxRepeating(str));
    }
}
 
// This code is contributed by Sudeep Mukherjee

Python 3

# Python 3 program to find the
# maximum consecutive repeating
# character in given string
 
# Returns the maximum repeating
# character in a given string
def maxRepeating(str):
 
    n = len(str)
    count = 0
    res = str[0]
    cur_count = 1
 
    # Traverse string except
    # last character
    for i in range(n):
         
        # If current character
        # matches with next
        if (i < n - 1 and
            str[i] == str[i + 1]):
            cur_count += 1
 
        # If doesn't match, update result
        # (if required) and reset count
        else:
            if cur_count > count:
                count = cur_count
                res = str[i]
            cur_count = 1
    return res
 
# Driver code
if __name__ == "__main__":
    str = "aaaabbaaccde"
    print(maxRepeating(str))
 
# This code is contributed
# by ChitraNayal

C#

// C# program to find the maximum
// consecutive repeating character
// in given string
using System;
 
class GFG
{
 
// function to find out the
// maximum repeating character
// in given string
static char maxRepeating(string str)
{
    int n = str.Length;
    int count = 0;
    char res = str[0];
    int cur_count = 1;
 
    // Traverse string except
    // last character
    for (int i = 0; i < n; i++)
    {
        // If current character
        // matches with next
        if (i < n - 1 &&
            str[i] == str[i + 1])
            cur_count++;
 
        // If doesn't match, update result
        // (if required) and reset count
        else
        {
            if (cur_count > count)
            {
                count = cur_count;
                res = str[i];
            }
            cur_count = 1;
        }
    }
    return res;
}
 
// Driver code
public static void Main()
{
    string str = "aaaabbaaccde";
    Console.Write(maxRepeating(str));
}
}
 
// This code is contributed
// by ChitraNayal

PHP

<?php
// PHP program to find the maximum
// consecutive repeating character
// in given string
 
// Returns the maximum repeating
// character in a given string
function maxRepeating($str)
{
    $n = strlen($str);
    $count = 0;
    $res = $str[0];
    $cur_count = 1;
 
    // Traverse string except
    // last character
    for ($i = 0; $i < $n; $i++)
    {
        // If current character
        // matches with next
        if ($i < $n - 1 &&
            $str[$i] == $str[$i + 1])
            $cur_count++;
 
        // If doesn't match, update result
        // (if required) and reset count
        else
        {
            if ($cur_count > $count)
            {
                $count = $cur_count;
                $res = $str[$i];
            }
            $cur_count = 1;
        }
    }
 
    return $res;
}
 
// Driver code
$str = "aaaabbaaccde";
echo maxRepeating($str);
 
// This code is contributed
// by ChitraNayal
?>

Javascript

<script>
 
// JavaScript program to find the maximum consecutive
// repeating character in given string
 
  // function to find out the maximum repeating
  // character in given string
function maxRepeating( str)
{
    var n = str.length;
    var count = 0;
    var res = str[0];
    var cur_count = 1;
 
    // Traverse string except last character
    for (var i=0; i<n; i++)
    {
        // If current character matches with next
        if (i < n-1 && str[i] == str[i+1])
            cur_count++;
 
        // If doesn't match, update result
        // (if required) and reset count
        else
        {
            if (cur_count > count)
            {
                count = cur_count;
                res = str[i];
            }
            cur_count = 1;
        }
    }
 
    return res;
}
 
var str = "aaaabbaaccde";
    document.write( maxRepeating(str));
 
</script>

Producción:  

a

Complejidad de tiempo: O(n) 
Complejidad de espacio: O(1)
Este artículo es una contribución de DANISH_RAZA . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a contribuir@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

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