一个面试题、求牛人指点…… 有一字符串,求最长的一个子字符串,该字符串由同一个字符组成,如aaababcccccccddeee求出最长连续相同字符 即ccccccc。。 最好能贴代码、、 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 提示一下$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 )) 来个循环的,坐等更好的算法。<?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); 好像有个小地方写错了。while($str{$j} && $str{$i} == $str{$j}) 本帖最后由 xuzuning 于 2011-10-21 19:03:01 编辑 混分$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) */ 表单提交 PHP 求图片大小异常 SQL-FRONT中存储过程字符类型转换的问题 function 里怎么用include(); 如何显示数据记录的序号(急,在线等) 能帮我看看吗,谢谢! 新课题,php,mysql,数组,大家帮忙给看看 关于计数器的问题!在线等待!! 300M以上的PHP网页空间+100M以上的MYMSQL空间。 php 与 $.get问题 PHP流行的设计模式是什么? 关于VSPHP调试模式 无法启动IE
print_r($r);Array
(
[0] => Array
(
[0] => aaa
[1] => ccccccc
[2] => dd
[3] => eee
) [1] => Array
(
[0] => a
[1] => c
[2] => d
[3] => e
))
$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);
$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
)
*/