我需要一个PHP代码来查找字符串中最长的连续字符序列

时间:2016-03-18 10:26:56

标签: php algorithm

我需要一个PHP代码来查找字符串中最长的连续字符序列。因此,如果b最多次合并,您的计划应echo bcount

示例字符串:

aaabababbbbbaaaaabbbbbbbbaa

输出必须是:

b 8

4 个答案:

答案 0 :(得分:5)

使用
- preg_match_all获取重复字符序列,
- array_mapstrlen一起获取每个序列的字符串长度
- max以获得数组中的最大值。

考虑以下示例:

$string =  "aaabababbbbbaaaaabbbbbbbbaa";

preg_match_all('#(\w)\1+#',$string,$matches);

print_r($matches);

将输出

Array
(
    [0] => Array
        (
            [0] => aaa
            [1] => bbbbb
            [2] => aaaaa
            [3] => bbbbbbbb
            [4] => aa
        )

    [1] => Array
        (
            [0] => a
            [1] => b
            [2] => a
            [3] => b
            [4] => a
        )

)

接下来,我们得到每个重复字符串的大小

$sizes = array_map('strlen', $matches[0]);
print_r($sizes);

将输出

Array
(
    [0] => 3
    [1] => 5
    [2] => 5
    [3] => 8
    [4] => 2
)

现在让我们获得$sizes数组的最大价值

print max($sizes);

会给我们

8

我们需要最大值的键才能拿到字母

$maxKey = array_keys($sizes, max($sizes));

print $matches[1][$maxKey[0]];

将输出

b

答案 1 :(得分:1)

由于您正在寻找连续序列:

$string = 'aaabababbbbbaaaaabbbbbbbbaa';

$count = strlen($string);
if ($count > 0)
{

    $mostFrequentChar = $curChar = $string[0];
    $maxFreq = $curFreq = 1;
    for ($i = 1; $i < $count; $i++)
    {
        if ($string[$i] == $curChar)
        {
            $curFreq++;
            if ($curFreq > $maxFreq)
            {
                $mostFrequentChar = $curChar;
                $maxFreq = $curFreq;
            }
        }
        else
        {
            $curChar = $string[$i];
            $curFreq = 1;
        }
    }

}

echo $mostFrequentChar . ' ' . $maxFreq;

答案 2 :(得分:0)

$string = 'aaabababbbbbaaaaabbbbbbbbaa';
$occurrence = [];

$count = strlen($string);
for ($x = 0; $x < $count; $x++) {
    if(isset($ocurrence[$string[$x]])) {
        $ocurrence[$string[$x]]++;
    } else {
        $ocurrence[$string[$x]] = 0;
    }
}

var_dump($occurrence);

这应该可以解决问题。

答案 3 :(得分:0)

<?php

 $x = "aaaaaaabbbbbbbaaaacccccccaaaaaaaaaaaaaaaaabbbbbbaaaaadddddddddddddddddddddddddddddddddd";
  $count  = strlen($x);

  $y =array();

     $n =0;
     $d =1;
    $first = $x{1};
 for($j = $d;$j < $count;$j++)
 {


        if($x{$j} == $first ) 
        {

        $y[$j] = $x{$j};
        $first = $x{$j}; 

        }
        elseif($x{$j} != $first ) 
        {

        $y[$j] = ",".$x{$j};
        $first = $x{$j}; 

        }



  }

   $xy  =   implode("",$y);
    $xy1     = explode(",",$xy);

     $c_count   = count($xy1);
      $dg = 1;
  for($g = 0;$g < $c_count;$g++) 
  {
       $cnt =   strlen($xy1[$g]); 
       $cntm =   $xy1[$g];
      $replace = $cntm{1};

         if($cnt > $dg)
         {
        $ab = str_replace($cntm,$replace,$cntm);
            $dg = $cnt.".".$ab ;


         }        
  }
   echo $dg;


?>