Problem
The count-and-say sequence is the sequence of integers with the first five terms as following:
1 |
|
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 where 1 ≤ n ≤ 30, 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:
1 |
|
1 |
|
Explanation 1
-
We initialize the
res
to 1 first, then ifn
is 2, we need to do 1 transformation; ifn
is 3, we need to do2
tranformation. -
During each transformation, we have a varialbe
temp
to keep track of the temporary result. After the tranformation, we updateres
to the transformation result; when we finish the loop, we return theres
string. -
In each transformation, start pointing from the first character of
res
, compare it with the next character, if they are the same, then updatecount
and move the pointer to the next character and repeat the process, until the current character to the end because there is no next character to compare, or until the current character is not the same as the next character. We append the count and the current character to theres
. Before we compare, we set thecount
back to 1. -
Finally return
res
as string.
Solution 1
1 |
|
Explanation 2
-
We can also use recursion to solve this problem. The base case for the main function is if the input number is 1, then we return string
"1"
immediately. Then we passn-1
to the main function to get the previous number’s result stringprevious
. For inputn
, we can get the result by just count and say the stringprevious
. -
Loop through the string
previous
using indexi
. Inside the loop, we create another variablej = i + 1
, and we useprevious[j]
to look behind comparing withprevious[i]
. Whileprevious[j] == previous[i]
, we increasej
. Outside the while loop, we can calculate thecount
isj - i
, the number wesay
isprevious[i]
. We append thecount
andsay
to the result string, then updatei = j
.
Solution 2
1 |
|