美文网首页
PHP 练习题

PHP 练习题

作者: 睡觉吹灯 | 来源:发表于2020-08-06 21:59 被阅读0次

PHP 练习题

有一个字符串 String s = "ababab",这个字符串可以看做 3 个 "ab" 构成,即 n = 3,L = "ab",s = nL。写一段程序,输入:"aaaaa",输出 6a;输入 ababa,输出:1ababa。

// 字符串替换的方式
protected function fun1($str) {
    $length = strlen($str);
    for ($i = 1; $i <= floor($length / 2); $i++) {
        if ($length % $i != 0) {
            continue;
        }
        $str1 = substr($str, 0, $i);
        if (str_replace($str1, '', $str) == '') {
            return $length / $i . $str1;
        }
    }
    return 1 . $str;
}
// 数组对比的方式
protected function fun($str) {
    $arr = str_split($str);
    $length = count($arr);
    for ($i = 1; $i <= floor($length / 2); $i++) {
        if ($length % $i != 0)
            continue;
        $j = 0;
        $k = 0;
        $s1 = '';
        while ($j <= $length - 1)  {
            $s1 = $s1 ?: join(array_slice($arr, $j, $i));
            $j += $i;
            $s2 = join(array_slice($arr, $j, $i));
            if ($s1 == $s2) {
                $k ++;
            } else {
                break;
            }
        }
        $k ++;
        if ($i * $k == $length) {
            return $k . $s1;
        }
    }
    return 1 . $str;
}

相关文章

网友评论

      本文标题:PHP 练习题

      本文链接:https://www.haomeiwen.com/subject/aqpziftx.html