LeetCode-38. Count and Say
来源:互联网 发布:公司申请软件著作权 编辑:程序博客网 时间:2024/06/05 21:01
问题:https://leetcode.com/problems/count-and-say/?tab=Description
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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 sequence.
Note: The sequence of integers will be represented as a string.
计数然后表达出来。n=1,输出1;n=2,之前有1个1,所以输出11;n=3,之前有两个1,输出21;n=4,之前是一个2,一个1,输出1211……给出n,输出第n个序列。结果也要用字符串的形式表示。
分析:如果n=1,返回”1”。如果n>1,需要用到迭代函数。遍历,如果前一个数和当前数相等,计数器加1.如果不等,得出当前的结果。
C++代码:
class Solution {public: string countAndSay(int n) { if (n == 1) { return string("1"); } string prev = countAndSay(n-1); int before = 0; int count = 0; string curr; for (int i = 0; i < prev.length(); ++i) { if (prev[i]-'0' == before) { count++; continue; } else if (before != 0) { curr.append(1, '0' + count); curr.append(1, '0' + before); } before = prev[i]-'0'; count = 1; } if (before != 0 && count != 0) { curr.append(1, '0' + count); curr.append(1, '0' + before); } return curr; }};
代码来自:http://blog.csdn.net/booirror/article/details/43736753
0 0
- [LeetCode]38.Count and Say
- LeetCode --- 38. Count and Say
- LeetCode 38.Count and Say
- [Leetcode] 38. Count and Say
- 38. Count and Say LeetCode
- Leetcode 38. Count and Say
- leetcode 38. Count and Say
- [leetcode] 38. Count and Say
- LeetCode-38.Count and Say
- LeetCode *** 38. Count and Say
- leetcode 38. Count and Say
- LeetCode-38. Count and Say
- LeetCode 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode - 38. Count and Say
- LeetCode 38. Count and Say
- Leetcode 38. Count and Say
- LeetCode 38. Count and Say
- Intellij idea 14支持ES6语言
- MySQL中的约束
- ubuntu14.04+indigo+primesense+Openni
- # Java基础入门
- View Controller Transition:京东加购物车效果
- LeetCode-38. Count and Say
- 52单片机控制指纹模块
- Ubuntu 16.04 LTS 成功编译 Android 6.0 源码教程
- pr_debug、dev_dbg等动态调试三
- .sh文件在/root 下直接执行(软连接)
- codeforces 363C
- 孙鑫网络编程code
- maven项目 main/java missing问题
- js内存泄漏问题