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.

C++:
01 string say(string s)
02 {
03     int n=s.size();
04     if(n==1){
05         s.insert(0,“1”);
06         return s;
07     }
08     int index=1;
09     char prv=s[0];
10     int cnt=1;
11     string t;
12     while(true){
13         while((index<n)&&(s[index]==prv)){
14             cnt++;
15             index++;
16         }
17         char tmp[32];
18         itoa(cnt,tmp,10);
19         t+=tmp;
20         t+=prv;
21         if(index>=n)
22             break;
23         prv=s[index++];
24         cnt=1;
25     }
26     return t;
27 }
28 
29 string countAndSay(int n) {
30     string tmp=“1”;
31     for(int i=2;i<=n;i++){
32         tmp=say(tmp);
33     }
34     return tmp;
35 }
Advertisements
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s