Count and Say
时间:2015-10-30 16:43:55
收藏:0
阅读:132
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.
class Solution { public: string countAndSay(int n) { stringstream result; int count = 0, i = 0; string tmp; if(n == 1) return "1"; else { tmp = countAndSay(n - 1); char now = tmp[0]; while(tmp[i]) { if(now == tmp[i]) { count++; ++i; } else { result << count << now; count = 1; now = tmp[i++]; } } result << count << now; return result.str(); } } };
- 注意最后result;防止tmp[i++] = ‘\n’时会跳过最后一个;
原文:http://www.cnblogs.com/dylqt/p/4923620.html
评论(0)