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.
本题的难点在于理解题目的意思。
最好的理解就是给出 111221之后的一个sample: 312211
如何理解呢? 将111221 拆成后面的表达式即可: 111, 22, 1 其中有 3个one , 2个two, 1个one ,读起来就是: 312211
1 class Solution { 2 public: 3 string countAndSay(int n) { 4 string a="1"; 5 if(n==1) return a; 6 for(int i=2;i<=n;i++) 7 { 8 string b; 9 char current = a[0]; 10 int j=1,count=1; 11 for(j=1;j<a.size();j++) 12 { 13 if(a[j]==current) 14 { 15 count++; 16 } 17 else 18 { 19 char c = count +'0'; 20 b+=c; 21 b+=current; 22 current = a[j]; 23 count=1; 24 } 25 } 26 char c = count+'0'; 27 b+=c; 28 b+=current; 29 a= b; 30 } 31 return a; 32 } 33 };
转载请注明出处: http://www.cnblogs.com/double-win/ 谢谢