欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

LeetCode - 38. Count and Say(36ms)

程序员文章站 2022-05-04 23:53:55
The count-and-say sequence is the sequence of integers with the first five terms as following: 1 is read off as "one 1" or 11.11 is read off as "two 1 ......

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