0%

count-and-say

Count and Say – LeetCode 38

Problem

Description

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

Example 1:

Input: 1
Output: “1”

Example 2:

Input: 4
Output: “1211”

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
string countAndSay(int n) {
string result;
for(unsigned i = 0; i != n; ++i){
if(i == 0) {result = "1"; continue;}
string update; unsigned count = 1;
for(unsigned j = 1; j != result.size(); ++j){
if(result[j-1] == result[j])
count++;
else{
update = update + (char)(count+'0') + result[j-1];
count = 1;
}
}
result = update + (char)(count+'0') + result[result.size()-1];
}
return result;
}
};

思路

使用一步一步算的笨办法。时间复杂度$O(n^{2})$,空间复杂度$O(n)$。
耗时$3$ ms,排名$63.40\%$

Better

思路

还没有看到更好的思路