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 generate(string s)
02 {
03     string result;
04     int n=s.size();
05     int i=0;
06     while(i<n)
07     {
08         char tmp=s[i];
09         int j=i;
10         while((j<n)&&(s[j]==tmp))
11         {
12             j++;
13         }
14         char count=ji+‘0’;
15         result+=count;
16         result+=tmp;
17         i=j;
18     }
19     return result;
20 }
21 class Solution {
22 public:
23     string countAndSay(int n) {
24         // Start typing your C/C++ solution below
25         // DO NOT write int main() function
26         string result=“1”;
27         for(int i=2;i<=n;i++)
28         {
29             result=generate(result);
30         }
31         return result;
32     }
33 };
Advertisements
This entry was posted in Recursive, 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