problem:
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.
String
thinking:
(1)首先要读懂计数 - 读数的规律,比较有意思
(2)对重复的数计数,单个的数读一个什么数。
code:
class Solution { public: string countAndSay(int n) { // string start = int_to_string(n); string start ="1"; for(int i=0;i<n-1;i++ ) start = factory(start); return start; } protected: string factory(string str) { int count=1;//初始化为1 ,很巧妙 string res; if(str.empty()) return str; if(str.size()==1) { res.push_back('1'); res+=str; return res; } for(string::size_type i=0;i<str.size()-1;i++)//计数到倒数第二个 { if(str.at(i)==str.at(i+1)) { count++; if(i==str.size()-2) //到了末尾,别忘了存储 { char a=count+'0'; res.push_back(a); res.push_back(str.at(i)); } } else { char a=count+'0'; res.push_back(a); res.push_back(str.at(i)); count=1; } }//size()-1 if(str.at(str.size()-1)!=str.at(str.size()-2))//处理最后一个字符 { res.push_back('1'); res.push_back(str.at(str.size()-1)); } // factory(res,n--); return res; } /* string int_to_string(int n) // int invert into string { vector<char> array; string res; if(n<0) n=-n; while(n>0) { int a = n%10; n/=10; char b = '0'+a; array.push_back(b); } for(int i=array.size()-1;i>=0;i--) res.push_back(array.at(i)); return res; } */ };
leetcode 题解 || Count and Say 问题
原文:http://blog.csdn.net/hustyangju/article/details/44624139