【Leetcode】Count and Say
2014-07-14 13:11
295 查看
【题目】
The count-and-say sequence is the sequence of integers beginning as follows:
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
【代码】
【总结】
1.思路:题目的意思是数字符个数然后说出来,每个字符的表达格式是:字符个数+字符本身。对于一个字符串,顺序扫描,统计个数,生成新的表达字符串。
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.
【代码】
class Solution { public: string countAndSay(int n) { if(n<=0) return ""; string str="1"; //str用来保存前一个状态的字符串 while(--n){ int count=1; string newStr=""; for(int i=0;i<str.length();++i){ if((i<str.length()-1)&&(str[i+1]==str[i])) ++count; else{ char cTemp=(char)(count+'0'); newStr+=cTemp; newStr+=str[i]; count=1; } } str=newStr; } return str; } };
【总结】
1.思路:题目的意思是数字符个数然后说出来,每个字符的表达格式是:字符个数+字符本身。对于一个字符串,顺序扫描,统计个数,生成新的表达字符串。
相关文章推荐
- 【LeetCode38】【Count and Say】StringBuilder
- LeetCode - Count and Say
- 【LeetCode】Count and Say 解题报告
- LeetCode Count and Say
- 【leetcode】【38】Count and Say
- Leetcode 之Count and Say(35)
- LeetCode(51)- Count and Say
- [LeetCode] Count and Say
- [C++]LeetCode: 20 Count and Say
- (leetCode)Count and Say --- 统计读
- [LeetCode]Count and Say
- LeetCode_Count and Say
- 【Leetcode】之Count and Say
- 【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 题解