有一字符串,求最长的一个子字符串,该字符串由同一个字符组成,如aaababcccccccddeee求出最长连续相同字符 即ccccccc
。。
 最好能贴代码、、

解决方案 »

  1.   

    提示一下$s = 'aaababcccccccddeee';preg_match_all('/(.)\\1+/', $s, $r);
    print_r($r);Array
    (
        [0] => Array
            (
                [0] => aaa
                [1] => ccccccc
                [2] => dd
                [3] => eee
            )    [1] => Array
            (
                [0] => a
                [1] => c
                [2] => d
                [3] => e
            ))
      

  2.   

    来个循环的,坐等更好的算法。<?php 
      $str = "aaababcccccccddeee";
      $start = 0;
      //$end = 0;
      $maxlen = 0;
      $leng = 0;
      $i = 0;
      while($str{$i}){
        $j = $i+1;
    while($str && $str{$i} == $str{$j}){
      $j++;
    }
        if($str{$j}){
      $len = $j-$i;
    }
    else{
      $len = $j-$i+1;
    }
    if($len > $maxlen){
       $maxlen = $len;
       $start = $i;
    }
    $i = $j;
      }
      echo "length:".$start."<br/>";
      echo "substring is:".substr($str,$start,$maxlen);
      

  3.   

    好像有个小地方写错了。while($str{$j} && $str{$i} == $str{$j})
      

  4.   

    本帖最后由 xuzuning 于 2011-10-21 19:03:01 编辑
      

  5.   

    混分$str = 'aaababbcccccccddeee';
    $count = strlen($str);
    $res = array();
    $cache = array();
    for ($i = 0; $i <= $count; $i++){//最后的字母须统计
    $cur = $str[$i];
    if ($str[$i] == $str[$i-1]){//连续,可直接累加记录
    if (empty($cache)){//没有缓存,则是首次出现字母
    ++$res[$cur];
    }
    else{//有缓存,则是已经存在的字母,第二次统计
    ++$cache[$cur];
    }
    }
    else{//不连续
    if (!empty($cache)){//如果存在缓存,则取cache数组里面的最大值
    list($key,$val) = each($cache);
    $res[$key] = max($res[$key],$val);
    unset($cache);//清空缓存
    }
    if (isset($res[$cur])){//存在历史记录
    ++$cache[$cur];
    }
    else{
    if (empty($cur)) break;
    ++$res[$cur];
    }
    }
    }
    echo '<pre>';
    print_r($res);
    echo '</pre>';
    /**
    Array
    (
        [a] => 3
        [b] => 2
        [c] => 7
        [d] => 2
        [e] => 3
    )
     */