To solve this problem, we need to generate the N-th term of the "look-and-say" sequence. The sequence starts with 1, and each subsequent term is a description of the previous term. For example, the term after 1 is "one 1" (11), then "two 1s" (21), then "one 2, one 1" (1211), and so on.
Approach
- Understand the Look-and-Say Sequence: Each term is formed by describing the previous term in terms of consecutive identical digits. For example, "1211" is described as "one 1, one 2, two 1s" → "111221".
- Generate the Sequence:
- Start with the first term ("1").
- For each subsequent term up to N, generate the next term by grouping consecutive identical digits and appending the count followed by the digit.
- Output the Result: The N-th term is the result, which we can directly print as a string (since it's a sequence of digits with no leading zeros).
Solution Code
def next_term(s):
result = []
count = 1
current = s[0]
for c in s[1:]:
if c == current:
count += 1
else:
result.append(str(count))
result.append(current)
current = c
count = 1
# Add the last group
result.append(str(count))
result.append(current)
return ''.join(result)
n = int(input())
if n == 1:
print(1)
else:
prev = '1'
for _ in range(2, n+1):
prev = next_term(prev)
print(prev)
Explanation
- Function
next_term: This function takes a strings(current term) and returns the next term in the sequence. It iterates through the string, counts consecutive identical digits, and constructs the next term by appending the count and digit for each group. - Main Logic:
- If N is 1, the result is directly "1".
- For N > 1, we start with the first term ("1") and generate each subsequent term using
next_termuntil we reach the N-th term. - Finally, we print the N-th term as a string (which is the correct output format).
This approach efficiently generates the sequence up to the N-th term, handling the constraints (N up to 30) with ease. The time complexity is O(M), where M is the length of the N-th term, which grows exponentially but is manageable for N up to 30. The space complexity is O(M) to store the current term.


作者声明:本文包含人工智能生成内容。