How to get the length of the longest sequence with the same characters in a string?

Indicate:

function getLength($str)
{
   //function i need
}
$str1 = 'aabbcccc'; 
$str2 = 'aabbccccaaaaa';
echo getLength($str1); //will get 4
echo getLength($str2); //will get 5

Any good ideas?

+1
source share
4 answers
function getLength($str)
{
  if (''===$str) return 0;
  preg_match_all('!(.)\\1*!', $str, $m);
  return max(array_map('strlen', $m[0]));
}
+11
source
function getLongestSequence($str)
{
   $sl = strlen($str);
   $longest = 0;
   for($i = 0; $i < $sl; )
   {
       $substr = substr($str, $i);
       $len = strspn($substr, $substr{0});
       if($len > $longest)
           $longest = $len;
       $i += $len;
   }

   return $longest;
}
+8
source

, , Regex substr:

function getLongestSequenceLength($string)
{
    $longest = $i = 0;
    $totalLength = strlen($string);
    while($i < $totalLength) {
        if(($length = strspn($string,  $string[$i], $i)) > $longest) {
            $longest = $length;
        }
        $i += $length;
    }
    return $longest;
}

, :

class Sequencer extends SplMaxHeap
{
    public function compare($a, $b) {
       return parent::compare(strlen($a), strlen($b));
    }
    public function key() {
        return strlen($this->current());
    }
    public function parseString($string)
    {
        $i = 0;
        $totalLength = strlen($string);
        while($i < $totalLength) {
            $length = strspn($string,  $string[$i], $i);
            $this->insert(str_repeat($string[$i], $length));
            $i += $length;
        }
    }
    public function getMaxLength()
    {
        $this->rewind();
        return strlen($this->top());
    }
}

SplMaxHeap ( 5.3), , , , :

$sequencer = new Sequencer;
$sequencer->parseString('aaabbbbcccccddddddeeeeeeeffffffggggghhhhiiijjk');

echo $sequencer->getMaxLength(); // 7
foreach($sequencer as $length => $sequence) {
    echo "$length => $sequence\n";
}
echo $sequencer->getMaxLength(); // RuntimeException

7 => eeeeeee
6 => dddddd
6 => ffffff
5 => ccccc
5 => ggggg
4 => hhhh
4 => bbbb
3 => iii
3 => aaa
2 => jj
1 => k
+3

You can get it pretty trivial, iterating through the lines one character at a time, tracking the last character you hit, and how many times you hit it. Also store the largest number of such; when you click on another character, check to see if you typed the new maximum consecutive character of the character, and if so, save it as a new maximum. Bring back the maximum when you went through the entire line.

+2
source

Source: https://habr.com/ru/post/1650831/


All Articles