Question:
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...
1
is read off as "one
or
1"11
.
11
is read off as "two
or
1s"21
.
21
is read off as "one
, then
2one 1"
or 1211
.
Given an integer n, generate the nth sequence.
Note: The sequence of integers will be represented as a string.
2读1,3读2,n读n-1,根据上面的规则。
Algorithm:
迭代
Accepted Code:
class Solution { public: string work(string s) { int k=0; string t; while(k<s.size()) { int tmp=s[k]; int count=0; while(s[k]==tmp) { k++; count++; } t.push_back(count+'0'); t.push_back(tmp); } return t; } string countAndSay(int n) { if(n==1)return "1"; string tmp="1"; while(--n) { tmp=work(tmp); //迭代 } return tmp; } };
时间: 2024-09-30 09:21:42