Look and Say 序列(PHP 实现)

 

Look and Say 序列如下所示:

1
11
21
1211
111221
312211
13112221
...

 

代码:

<?php
/*
 * @param $s string 需要统计的字符串
 * @return 统计完成的字符串
 */
function look_and_say($s) {

    $length = 1;//初始长度
    $tmp = $s[0];//将要统计的字符串
    $return = '';//将要返回的字符串初始值设为空字符串

    for($i = 1; $i < strlen($s); $i++) {
        if($tmp == $s[$i]) {
            $length++;
        } else {
            $return .= $length.$tmp;
            $tmp = $s[$i];    
            $length = 1;
        }
    }
    $return .= $length.$tmp;
    return $return;
}

for($i = 0, $s = 1; $i < 10; $i++) {
    $s = look_and_say($s);
    print $s.PHP_EOL;
}

 

 

 

 

 

 

 

参考:《PHP 经典实例》

posted @ 2016-03-02 22:18  nemo20  阅读(176)  评论(0)    收藏  举报
访客数:AmazingCounters.com
2016/05/17 起统计