报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:
1, 11, 21, 1211, 111221, ...
1
读作 "one 1"
-> 11
.
11
读作 "two 1s"
-> 21
.
21
读作 "one 2, then one 1"
-> 1211
.
给定一个整数 n
, 返回 第 n
个顺序。
样例
给定 n = 5
, 返回 "111221"
.
解题思路:
采用双指针法,第一个指针p1指向当前数字,第二个指针p2指向与当前数字不同的第一个位置,p2-p1的值就为此数字的个数,就能计算出下一个报数了。具体代码有注释。
class Solution { public: /** * @param n: the nth * @return: the nth sequence */ string countAndSay(int n) { // write your code here vector<string> res;//存放结果 string s = "1";//初始解 for(int i=0;i<n;i++)//循环求解存放结果 { res.push_back(s);//将当前结果存进res int p1 = 0;//双指针法,前一个指针 int p2 = 1;//后一个指针,指向与前一指针数字第一个不同的位置 string temp = s;//将上一个结果暂存,后面要用 s.clear();//清空当前结果,计算下一个结果 //以下程序是根据上一个数字进行报数,求出下一个数 while(p2 <= temp.size()) { if(temp[p1] != temp[p2]) { s += to_string(p2-p1); s += temp[p1]; p1 = p2; p2++; } else p2++; } } return res[n-1]; } };