LeetCode: Count and Say [037]
2014-05-20 08:35
225 查看
【题目】
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
1is read off as
"one 1"or
11.
11is read off as
"two 1s"or
21.
21is 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.
【题意】
有一个这样的序列,序列中的每个数都是从前一个数通过count-and-say规则生成。所谓count-and-say就是数数然后读出来,按照读法来组织新的数。举个例子来说
1 读成“1个1” ==> 11
11 读成“2个1” ==> 21
21 读成“1个2,1个1” ==> 1211
目标是返回序列中的第n个数
【思路】
按规则顺序生成序列中的前n个数【代码】
class Solution { public: string getNext(string integer){ int count=0; char digit='\0'; string newInteger=""; for(int i=0; i<integer.length(); i++){ if(integer[i]!=digit){ if(digit!='\0'){ char countChar='0'+count; newInteger+=countChar; newInteger+=digit; } count=1; digit=integer[i]; } else{ count++; } } if(digit!='\0'){ char countChar='0'+count; newInteger+=countChar; newInteger+=digit; } return newInteger; } string countAndSay(int n) { int count=1; string integer="1"; if(n<1)return ""; //考虑一些非法值,题目没有规定,那就设定为空 if(n==1)return integer; while(count<n){ integer=getNext(integer); count++; } return integer; } };
相关文章推荐
- 【LeetCode】Count and Say
- 37 leetcode - Count and Say
- leetcode - Count and Say
- Leetcode 38 Count and Say
- Count and Say-LeetCode
- int转string与LeetCode:Count and Say
- leetcode - Count and Say
- Leetcode 38 Count and Say
- leetcode记录——Count and Say
- leetcode--Count and Say
- [LeetCode]Count and Say
- [LeetCode] Count and Say 计数和读法
- 【Leetcode】【Easy】Count and Say
- [LeetCode]—Count and Say 读数字
- leetcode 38:Count and Say
- 【Leetcode】Count and Say
- 开始刷leetcode day30:Count and Say
- leetcode-Count and Say
- [LeetCode]Count and Say
- LEETCODE-Count and Say