[LeetCode]Count and Say

又一道模擬題,按照必定規律生成字符串,求第n個字符串ide

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.blog

Note: The sequence of integers will be represented as a string.字符串

稍稍解釋一下字符串的生成規律:字符串從「1」開始,第i+1個字符串是第i個字符串數字形式的讀法。string

生成規律就是代碼思路~用prev記錄第i個字符串,cur爲第i+1個字符串。io

逐個訪問prev的元素並進行統計。c爲當前字符,count爲c連續出現的個數。event

當前訪問的元素prev[i]與c不一樣時,將count, c轉化成字符串格式,插入cur中;更新c和count. class

代碼test

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6 
 7         string prev = "1";
 8         string cur = "";
 9         for(int i=2; i<=n; ++i)
10         {
11             int p=1; 
12             int len = prev.length();
13             char c = prev[0];
14             int count = 1;
15             while(p<len)
16             {
17                 if(c==prev[p])
18                 {
19                     ++p; ++count;
20                 }
21                 else{
22                     cur += '0'+count;
23                     cur += c;
24                     count = 1;
25                     c = prev[p++];
26                 }
27             }
28             cur += '0'+count;
29             cur += c;
30             prev = cur;
31             cur = "";
32         }
33         return prev;
34     }
35 };
View Code
相關文章
相關標籤/搜索