请求开发判断字符串中是否存在符合特定连续数字规则的函数
Solution: Check for Consecutive Digit Runs Matching Their Value
Got it, let's break down how to solve this problem. The task is to write a function that takes a string (which has at least one character and includes digits 2-5) and returns "true" if any digit d (where 2 ≤ d ≤ 5) appears consecutively at least d times. If no such digit exists, return "false".
Approach
Here's a straightforward, efficient way to handle this:
- Track the current digit we're counting and how many times it's appeared consecutively.
- As we iterate through the string:
- If the next character matches the current digit, increment the count.
- If it doesn't, check if the current digit meets our criteria (is 2-5, and count ≥ digit value). If yes, return "true" immediately.
- Reset our tracking variables to the new digit and start counting from 1.
- Don't forget to check the last sequence of digits after the loop finishes—we might not have checked it yet!
Code Example (Python)
def check_consecutive_digit_requirement(input_str): # Defensive check (though the problem states input has at least one element) if not input_str: return "false" # Initialize tracking variables with the first character current_digit = input_str[0] consecutive_count = 1 for char in input_str[1:]: if char == current_digit: consecutive_count += 1 else: # Check if the current sequence meets the criteria digit_value = int(current_digit) if 2 <= digit_value <= 5 and consecutive_count >= digit_value: return "true" # Reset for the new digit current_digit = char consecutive_count = 1 # Check the final sequence after loop ends final_digit_value = int(current_digit) if 2 <= final_digit_value <= 5 and consecutive_count >= final_digit_value: return "true" # No valid sequences found return "false"
Test Cases
Let's verify with your examples:
- Input:
"555123"→ The digit 5 runs 3 times (3 < 5), digits 2 and 3 each run once. No valid sequences, so returns"false". - Input:
"57333"→ The digit 3 runs exactly 3 times (3 ≥ 3), so returns"true".
Additional Edge Cases to Consider
"22"→ Returns"true"(2 runs 2 times)"444"→ Returns"false"(4 runs 3 times, which is less than 4)"55555"→ Returns"true"(5 runs 5 times)"332222"→ Returns"true"(2 runs 4 times, which meets the ≥2 requirement)
内容的提问来源于stack exchange,提问作者chopin_is_the_best
相关产品推荐
相关产品推荐

