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
resto 1 first, then ifnis 2, we need to do 1 transformation; ifnis 3, we need to do2tranformation. -
During each transformation, we have a varialbe
tempto keep track of the temporary result. After the tranformation, we updateresto the transformation result; when we finish the loop, we return theresstring. -
In each transformation, start pointing from the first character of
res, compare it with the next character, if they are the same, then updatecountand 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 thecountback to 1. -
Finally return
resas 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-1to 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
previoususing 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 thecountisj - i, the number wesayisprevious[i]. We append thecountandsayto the result string, then updatei = j.
Solution 2
1 | |