https://leetcode.com/problems/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.

 

思路:

题意有些模糊,看明白1211到111221就懂了。

 

AC代码:

 1 class Solution {
 2 public:
 3     string countAndSay(int n) {
 4         int tmp_n,count,k;
 5         string tmp,tmp_res,a[n];
 6         a[0]="1";
 7         for(int i=1;i<n;i++){
 8             tmp=a[i-1];
 9             tmp_res="";
10             tmp_n=tmp.size();
11             k=0;
12             count=1;
13             for(int j=1;j<tmp_n;j++){
14                 if(tmp[j]==tmp[j-1]){
15                     count++;
16                     continue;
17                 }
18                 else{
19                     tmp_res.push_back('0'+count);
20                     tmp_res.push_back(tmp[j-1]);
21                     count=1;
22                 }
23             }
24             tmp_res.push_back('0'+count);
25             tmp_res.push_back(tmp[tmp_n-1]);
26             a[i]=tmp_res;  
27         }
28     return a[n-1];
29     }
30 };