[LeetCode]Count and Say

又一道模拟题,按照一定规律生成字符串,求第n个字符串

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.

稍稍解释一下字符串的生成规律:字符串从“1”开始,第i+1个字符串是第i个字符串数字形式的读法。

生成规律就是代码思路~用prev记录第i个字符串,cur为第i+1个字符串。

逐个访问prev的元素并进行统计。c为当前字符,count为c连续出现的个数。

当前访问的元素prev[i]与c不同时,将count, c转化成字符串格式,插入cur中;更新c和count. 

代码

 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

 

posted @ 2013-10-28 13:23  Apprentice.Z  阅读(527)  评论(0编辑  收藏  举报