LZ_Jaja

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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 };

 

posted on 2018-07-30 15:02  LZ_Jaja  阅读(180)  评论(0编辑  收藏  举报