Count and Say

来源:互联网 发布:网络电商平台 编辑:程序博客网 时间:2024/06/06 01:26

The count-and-say sequence is the sequence of integers with the first five terms as following:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221

1 is read off as “one 1” or 11. (1个1)
11 is read off as “two 1s” or 21.(2个1)
21 is read off as “one 2, then one 1” or 1211.(1个2, 1个1)

Given an integer n, generate the nth term of the count-and-say sequence.

PHP代码实现如下:

// 给定一个字符串,输出下一个值function lookAndSay($str) {    $len = strlen($str);    $count = 0;    $result = '';    $tmp = $str[0];    for ($i = 0; $i < $len; $i++) {        if ($tmp != $str[$i]) {            $result .= $count . $tmp;            $tmp = $str[$i];            $count = 1;        } else {            $count++;        }    }    $result .= $count . $tmp;    return $result;}//echo lookAndSay('21');
// 输出n层,或者第n个function countAndSay($n) {    if ($n == 1) {        echo '1'.'<br>';        return '1';    }    $tmp = countAndSay($n - 1);    $c = $tmp[0];    $count = 1;    $res = '';    for ($i = 1; $i < strlen($tmp); $i++) {        if ($tmp[$i] == $c) {            $count++;        } else {            $res .= $count . $c;            $c = $tmp[$i];            $count = 1;        }    }    $res .= $count . $c;    echo $res . '<br>';    return $res;}countAndSay(6);