drju37335 2014-03-25 06:40
浏览 96
已采纳

如何在不使用任何内置php函数的情况下搜索字符串中连续重复的字符?

I have been asked to solve this question. Please suggest me how to solve this.

$string = "kkjnmnmnjjjnmn";

here I need to find consecutively repeated string of length 3. for example - kkj has occurred only once and jnm 2 times and nmn 3 times.

Starting from first character, going in right side direction, 3 consecutive characters which are repeated more than once should be the output.

Preg_match_all will result as nmn - 2 times and not as 3 times.

How to solve this?

  • 写回答

4条回答 默认 最新

  • duanbei3747 2014-03-25 06:49
    关注
        $string = "kkjnmnmnjjjnmn";
        $length = strlen($string);
        $pieces = [];
        for ($i = 0; $i < $length - 2; $i++) {
            $piece = substr($string, $i, 3);
            if (array_key_exists($piece, $pieces)) {
                $pieces[$piece] += 1;
            } else {
                $pieces[$piece] = 1;
            }
        }
    

    // $pieces will contain what you need

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动