how to get the index (of origin 0) of the highest repetition within a string in php

0

Ex: Run::posicaoMaiorRepeticao(‘ccddddeee') should return 2, since dddd is the longest repetition and its initial index is 2.

I got here, but the main function still could not do:

class Run
{
    public static function posicaoMaiorRepeticao($str)
    {
        throw new Exception(‘Implementar’);
    }
}

echo Run:: posicaoMaiorRepeticao('abbcccddddeeeeeefffffffffggg');
// 16


echo Run:: posicaoMaiorRepeticao('ddddeeeeeefffffffffgggggggggggggggggghhhhh’);
// 19
    
asked by anonymous 02.07.2017 / 18:42

2 answers

0
  

This does not work with multibyte characters!

In the post condition could simply do:

$string = 'ddddeeeeeefffffffffgggggggggggggggggghhhhh';

$QntPorCaractere = count_chars($string, 1);

arsort($QntPorCaractere);
reset($QntPorCaractere);

echo strpos($string, key($QntPorCaractere));

Try this.

This will return the position of the first one of the most repeating letter in the string. That is, if it is gabcdefggg it would be 0 , because g is the one that repeats the most and the first position of g is 0 .

The count_chars using the 1 parameter will return exactly the number of occurrences (in the value) and what was the character (in the key) of the array, that is:

array(5) {
  [100]=>
  int(4)
  [101]=>
  int(6)
  [102]=>
  int(9)
  [103]=>
  int(18)
  [104]=>
  int(5)
}

In this case, the 103 is the g , in the ASCII table, so we can sort, after all we want the one that has more occurrences, we use arsort() .

Then we get the 103 , which is contained in the array key using key($QntPorCaractere) and we use it inside the strpos() that takes the first occurrence.

It may seem wrong to use strpos($string, 103); instead of using something like strpos($string, pack('C', 103)); . But the PHP manual says "If needle is not a string, it is converted to an integer and applied to the ordinal value of a character.", So since it is in the int format the 103 passes to g internally by strpos .

    
02.07.2017 / 19:13
0

I do not know if there is any function of php to do this in a more practical way, but I did a very simple algorithm that does this:

<?php
function posicaoMaiorRepeticao($x)
{
    $index = -1;
    for ($i=0;$i<strlen($x);$i++)
    {
        if ($ultimo != $x[$i])
        {
            $ultimocount = $count;
            $count = 0;
            $ultimo = $x[$i];
        }
        else
        {
            $count++;
            if ($count > $ultimocount)
                $index = strpos($x, $x[$i]);
        }
    }
    return $index;
}

$n = "abbcccddddeeeeeefffffffffggg";
echo posicaoMaiorRepeticao($n); //Output: 16

See working at Ideone .

    
02.07.2017 / 19:23