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.
題目描述的不是很清楚,其實就是第i+1個字串是第i個字串的讀法,第一字串為 “1”
比如第四個字串是1211,它的讀法是 1個1、1個2,2個1,因此第五個字串是111221。
第五個字串的讀法是:3個1、2個2、1個1,因此第六個字串是312211 本文地址
......
簡單的模擬就可以。
1 class Solution { 2 public: 3 string countAndSay(int n) { 4 if(n < 1)return ""; 5 string prev = "1"; 6 for(int i = 2; i <= n; i++) 7 { 8 char curChar = prev[0]; 9 int times = 1;//curChar 出現的次數 10 string tmpstr; 11 prev.push_back('#');//處理邊界條件 12 for(int k = 1; k < prev.size(); k++) 13 { 14 if(prev[k] == curChar) 15 times++; 16 else 17 { 18 tmpstr += to_string(times); 19 tmpstr.push_back(curChar); 20 curChar = prev[k]; 21 times = 1; 22 } 23 } 24 prev = tmpstr; 25 } 26 return prev; 27 } 28 };
其實我們可以發現字串中永遠只會出現1,2,3這三個字元,假設第k個字串中出現了4,那麼第k-1個字串必定有四個相同的字元連續出現,假設這個字元為1,則第k-1個字串為x1111y。第k-1個字串是第k-2個字串的讀法,即第k-2個字串可以讀為“x個1,1個1,1個y” 或者“*個x,1個1,1個1,y個*”,這兩種讀法分別可以合併成“x+1個1,1個y” 和 “*個x,2個1,y個*”,代表的字串分別是“(x+1)11y” 和 "x21y",即k-1個字串為“(x+1)11y” 或 "x21y",不可能為“x1111y”.
【版權宣告】轉載請註明出處:http://www.cnblogs.com/TenosDoIt/p/3776356.html