标签:
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.
新建的函数目的是为了计算每上一个的1和2 的数量。
1 class Solution { 2 public: 3 string unguarded_convert(const string &say) 4 { 5 stringstream ss; 6 int count = 0; 7 char last = say[0]; 8 9 for (size_t i = 0; i <= say.size(); ++i) 10 { 11 if (say[i] == last) 12 { 13 ++count; 14 } 15 else 16 { 17 ss << count << last; 18 count = 1; 19 last = say[i]; 20 } 21 } 22 23 return ss.str(); 24 } 25 26 string countAndSay(int n) 27 { 28 if (n <= 0) return string(); 29 30 string say = "1"; 31 32 for (int i = 1; i < n; ++i) 33 { 34 say = unguarded_convert(say); 35 } 36 37 return say; 38 } 39 };
标签:
原文地址:http://www.cnblogs.com/zongmeng/p/4378940.html