[leetcode] Count and Say
2015-01-20 10:41
295 查看
Count and Say
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.
思路:
举例说明怎么做,求 s=1211 的下一个,用res记录。从下标1开始遍历这个字符串,下标0作为比较字符。将s[1]与s[0]比较,不等,于是s[0]只重复了一次,因此就是1个s[0],此时res=11。再将s[2]与s[1]比较,还是不等,res=1112。s[3]与s[2]比较,相等,即s[2]重复了两次,也就是2个s[2],此时res=111221。有一个需要注意的地方,遍历s的时候最后添加的是倒数第二个不重复的字符,最后的那些重复的字符只是与前面进行比较并没有添加到res中。因此在遍历完成后,还需要添加最后那些重复的字符。
题解:
class Solution { public: string fun(string s) { string str; int count = 1; char pre = s[0]; char tmp; for(int i=1;i<s.size();i++) { if(s[i]==pre) count++; else { tmp = count+'0'; str = str+tmp+pre; count = 1; pre = s[i]; } } tmp = count+'0'; str = str+tmp+pre; return str; } string countAndSay(int n) { string res = "1"; for(int i=1;i<n;i++) res = fun(res); return res; } };
View Code
相关文章推荐
- LeetCode Count and Say
- 【LeetCode】Count and Say
- [LeetCode]Count and Say
- leetcode之路038 Count and Say
- leetcode Count and Say
- LeetCode: count and say
- LeetCode(38) Count and Say
- 【LeetCode】Count and Say
- Count and Say 【leetcode】
- [leetcode]_Count and Say
- [LeetCode]Count and Say
- [leetcode-38]count and say(java)
- 【Leetcode】Count and Say
- Leetcode - Count and Say
- leetcode第17题----- Count and Say
- LeetCode(51)- Count and Say
- leetcode-38-Count and Say 基础题
- Leetcode之Count and Say 问题
- LeetCode(38)--Count and Say
- LeetCode038 Count and Say