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
- 11
- 21
- 1211
- 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);
阅读全文
0 0
- LeetCode: Count and Say
- [LeetCode]Count and Say
- LeetCode Count and Say
- [Leetcode] Count and Say
- Count and Say
- Leetcode: Count and Say
- [LeetCode] Count and Say
- LeetCode Count and Say
- Count and Say
- [38]Count and Say
- Count and Say
- Count and Say
- Count and Say
- [LeetCode]Count and Say
- Count and Say
- Count and Say
- [LeetCode] Count and Say
- LeetCode-Count and Say
- 【JavaScript】我的第4个例子-实例解析
- 使用Nexus搭建Maven私服(二)
- OpenCV学习(3) OpenCV框架
- Unity 播放、停止播放、循环播放音频(笔记)
- 一个简单的网络通信程序
- Count and Say
- Shell $0, $#, $*, $@, $?, $$
- MaterialDesign学习篇(六),调色板Palette的学习
- Apache配置虚拟域名
- Docker界面管理工具
- QT5 多语言设计及键盘控制
- 回声消除的原理和应用场景
- can't be deserialize the current JSON arry (e.g[1,2,3])into type [···] because the type requires a J
- Android平台下OpenGL初步