LeetCode:Count and Say


題目鏈接

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

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM