The count-and-say sequence is a sequence of strings where each term is obtained from the previous term by counting the number of repeating characters and stating the count followed by the character itself. The first term in the sequence is "1".
Write a function countAndSay(n: int) -> str
that takes an integer n
as input and returns the nth term of the count-and-say sequence.
Input: n = 4
Output: "1211"
Explanation: The sequence starts as "1", "11", "21", and "1211".
n
is guaranteed to be in the range [1, 30]
.You can assume that the count-and-say sequence will never exceed 30 terms.
We can solve this problem iteratively using a loop. Here is the step-by-step explanation of the solution:
Create a variable current_string
and set it to "1". This will store the current term of the sequence.
Iterate n - 1
times to generate the next term of the sequence. We subtract 1 from n
because we already have the first term.
Inside the loop, create a variable next_string
and initialize it as an empty string. This will store the next term of the sequence.
Iterate through each character char
in the current_string
.
Create two variables count
and current_char
, and initialize them with values 1 and char
respectively. These will keep track of the count of repeating characters and the current character being counted.
While the next character is equal to current_char
, increment the count
and move to the next character.
Append the string representation of count
followed by current_char
to next_string
.
Assign next_string
to current_string
for the next iteration.
Finally, return current_string
which will contain the nth term of the count-and-say sequence.
Here is the Python implementation of the countAndSay
function:
def countAndSay(n: int) -> str:
current_string = "1"
for _ in range(n - 1):
next_string = ""
i = 0
while i < len(current_string):
count = 1
current_char = current_string[i]
while i + 1 < len(current_string) and current_string[i+1] == current_char:
count += 1
i += 1
next_string += str(count) + current_char
i += 1
current_string = next_string
return current_string
By calling countAndSay(4)
, the function will return "1211"
as the fourth term of the count-and-say sequence.