題目
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.
解題之法
class Solution {
public:
string getNext(string s)
{
if (s == "") return "1";
string ans = "";
int len = s.size(), cnt = 1; // 計數cnt初始為1,因為一旦出現一個數那至少是一次
for (int i = 0; i < len; i++)
{
if (i+1 < len && s[i+1] == s[i])
{
cnt++;continue;
}
ans += cnt + '0'; // 和下面的s[i]要分開來加,否則會先進行字符串相加再到ans中
ans += s[i];
cnt = 1; //記錄后記得將cnt恢復為1
}
return ans;
}
string countAndSay(int n)
{
if (n == 0)
return "";
string ans = "";
for (int i = 0; i < n; ++i) // 重復找n次next的就可以了
ans = getNext(ans);
return ans;
}
};
分析
題目的意思是按照一定的規則出現數字,以字符串的形式。規定第一個是1,接下去就是按照前一個數的讀法記錄,所以第二個就是1個1,記錄為11,那第三個就是對11的讀法就是2個1,記錄為21,第四個就是對21的讀法,一個2一個1,記錄為1211,以此類推。