The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     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 term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

Example 1:

Input: 1
Output: "1"

 

Example 2:

Input: 4
Output: "1211"
 1 class Solution {
 2 public:
 3     string countS(string s) {
 4         int l = s.length();
 5         char curChar = s[0];
 6         string retStr = "";
 7         int curN = 0;
 8         for (int i = 0; i < l; i++) {
 9             if (curChar == s[i]) {
10                 curN += 1;
11                 if (i == l - 1) {
12                     char temp = curN + '0';
13                     retStr = retStr + temp + curChar;
14                 }
15             }
16             else {
17                 char temp = curN + '0';
18                 retStr = retStr + temp + curChar;
19                 curChar = s[i];
20                 curN = 1;
21                 if (i == l - 1) {
22                     retStr = retStr + '1' + curChar;
23                 }
24             }
25         }
26         return retStr;
27     }
28 
29     string countAndSay(int n) {
30         if (n == 1) {
31             return "1";
32         }
33         else {
34             string s = "1";
35             for (int i = 2; i <= n; i++) {
36                 s = countS(s);
37             }
38             return s;
39         }
40     }
41 };

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程

3766 8.82元 9.8元 9折