38. Count and Say
来源:互联网 发布:java 解析swf 编辑:程序博客网 时间:2024/06/15 21:16
The count-and-say sequence is the sequence of integers with the first five terms as following:
1. 12. 113. 214. 12115. 111221
1 is read off as “one 1” or 11.
11 is read off as “two 1s” or 21.
21 is read off as “one 2, then one 1” or 1211.
Given an integer n, generate the nth term of the count-and-say sequence.
Note: Each term of the sequence of integers will be represented as a string.
Example 1:
Input: 1Output: "1"
Example 2:
Input: 4Output: "1211"
这道题最简单的思路就是遍历上一个字符串,统计相同字符连续出现的次数,然后输出次数和字符。但是实现的时候很容易出错,需要细心判断在什么情况下才需要输出。
class Solution {public: string countAndSay(int n) { if (n == 1) return "1"; //第n-1个字符串 string last = "1"; for (int i = 2; i <= n; i++) { //第n个字符串 string tmp; //用来统计c连续出现的次数 int count = 0; char c = last[0]; for (int j = 0; j < last.size(); j++) { if (last[j] == c) { count++; } else { tmp += (count + '0'); tmp += c; c = last[j]; count = 1; } //注意当遍历到最后一个时也要输出 if (j + 1 == last.size()) { tmp += (count + '0'); tmp += c; } } last = tmp; } return last; }};
阅读全文
0 0
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- 38. Count and Say
- HDU1423 Greatest Common Increasing Subsequence(最长公共递增子序列)
- 数据库那点事(Mysql)-5
- github删除某个文件夹(文件)
- GCC/G++ + sublime text3 + powershell在windows使用指南
- 台湾大学机器学习基石lecture1小结
- 38. Count and Say
- ajax跨域,以及在laravel中实现跨域
- ArrayList的学习笔记
- JQuery实现注册表单页面 4 代码
- Shell脚本中获取本机ip地址的3个方法
- usaco-4.2.2The Perfect Stall完美的牛栏
- 面向对象——封装性
- Codeforces Similar Words [trie树+树形dp]
- 虚拟路径配置