題目連接html
The count-and-say sequence is the sequence of integers beginning as follows:1, 11, 21, 1211, 111221, ...
spa
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
.code
Given an integer n, generate the nth sequence.htm
Note: The sequence of integers will be represented as a string.blog
題目描述的不是很清楚,其實就是第i+1個字符串是第i個字符串的讀法,第一字符串爲 「1」leetcode
好比第四個字符串是1211,它的讀法是 1個一、1個2,2個1,所以第五個字符串是111221。字符串
第五個字符串的讀法是:3個一、2個二、1個1,所以第六個字符串是312211 本文地址get
......string
簡單的模擬就能夠。io
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