原题:函数
The count-and-say sequence is the sequence of integers beginning as follows: 1, 11, 21, 1211, 111221, ...code
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.blog
题意大体意思是根据每一个数字的多少构成下一个数字,解题关键在于对每一位的数字进行标记,明确每一个数字出现次数,这样 次数+数字构成下一次数字。leetcode
该代码思路思路比较直接,经过统计数字的个数进行输出。get
class Solution { public: string read2sayArray(int n) { string s="1"; string strtemp; char temp; for(int i=0;i<n-1;i++) { int len=1; for(size_t i = 0;i<s.size();) { if(s[i+len]!='\0')//不是最后一个字符 { if(s[i]==s[i+len])//同一个字符 { len=len+1; //继续查看下一个字符 continue; } else//不等 输出统计结果 { temp=len+'0'; strtemp+=temp; strtemp+=s[i]; i=i+len;//继续下面的查找 len=1; } } else//结束 { temp=len+'0'; strtemp+=temp; strtemp+=s[i]; len=1; break; } } s=strtemp; strtemp=""; } return s; } };
在leetcode上面看到直接用STL函数的,简洁很多。string
class Solution { public: string countAndSay(int n) { string s("1"); while (--n) s = getNext(s); return s; } string getNext(const string &s) { stringstream ss; for (auto i = s.begin(); i != s.end(); ) { auto j = find_if(i, s.end(), bind1st(not_equal_to<char>(), *i)); //bind1st找到不相等的位置输出 ss << distance(i, j) << *i;
//distance 返回两者迭代器之间距离 i = j; } return ss.str(); } };
两种思路的验证结果是相同的。io
结论:利用STL提升代码可读性和效率;class
find_if(i, s.end(), bind1st(not_equal_to<char>(), *i));查找返回和迭代器i不相等的位置效率