如何获取字符串中具有相同字符的最长序列的长度?

时间:2010-05-10 15:16:31

标签: php string count

待指定:

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

有什么好主意吗?

4 个答案:

答案 0 :(得分:11)

function getLength($str)
{
  if (''===$str) return 0;
  preg_match_all('!(.)\\1*!', $str, $m);
  return max(array_map('strlen', $m[0]));
}

答案 1 :(得分:9)

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;
}

答案 2 :(得分:4)

以下是我对它的看法,它应该比正则表达式和提供的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 :(得分:2)

你可以通过一次遍历字符串一个字符,跟踪你击中的最后一个字符以及你击中它的次数来平凡地得到这个。还存储最多的那些;当你点击不同的角色时,检查你是否达到了新的最大连续字符数,如果是,则将其存储为新的最大值。当你完成整个字符串时,返回最大值。