C++
1 class Solution { 2 public: 3 /** 4 * @param n the nth 5 * @return the nth sequence 6 */ 7 string countAndSay(int n) { 8 // Write your code here 9 if (0 == n) { 10 return ""; 11 } 12 string pre = "1"; 13 for (int i = 1; i < n; i++) {//从第2个(i=1)开始 14 char ch = pre[0]; 15 string cur = ""; 16 int cnt = 0; 17 for (int j = 0; j < pre.size(); j++) { 18 if (pre[j] == ch) { 19 cnt ++; 20 } else { 21 cur = cur + itostr(cnt) + ch; 22 ch = pre[j]; 23 cnt = 1; 24 } 25 } 26 if (cnt != 0) {//处理后边的字符 27 cur = cur + itostr(cnt) + ch; 28 } 29 pre = cur; 30 cur = ""; 31 } 32 return pre; 33 34 } 35 string itostr(int i) {//自定义int转string函数 36 char str[10]; 37 //itoa(str,i,10);->only support Windows 38 sprintf(str, "%d", i);//support any platforms 39 return str; 40 } 41 };
本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5000386.html,如需转载请自行联系原作者