Example input
Longest Alternating Substring:
Given a string of digits, return the longest substring with alternating odd/even or even/odd digits. If two or more substrings have the same length, return the substring that occurs first.
Examples:
longest_substring("225424272163254474441338664823") ➞ "272163254"
# substrings = 254, 272163254, 474, 41, 38, 23
longest_substring("594127169973391692147228678476") ➞ "16921472"
# substrings = 94127, 169, 16921472, 678, 476
longest_substring("721449827599186159274227324466") ➞ "7214"
# substrings = 7214, 498, 27, 18, 61, 9274, 27, 32
# 7214 and 9274 have the same length, but 7214 occurs first.
Notes:
The minimum alternating substring size is 2, and there will always be at least one alternating substring.
Example output
To solve this problem, we can use a sliding window approach where we keep track of the current alternating substring and the longest alternating substring seen so far. We can start with a window of size 2 and then move the window by 1 position at a time until we reach the end of the string.
Within each window, we can check if the substring is alternating by checking if the first digit is odd and the second digit is even, or if the first digit is even and the second digit is odd. If the substring is alternating, we update the longest alternating substring seen so far.
Here's the Python code that implements this approach:
def longest_substring(digits):
max_len = 0
max_substr = ""
for i in range(len(digits) - 1):
if (int(digits[i]) % 2 == 0 and int(digits[i+1]) % 2 == 1) or (int(digits[i]) % 2 == 1 and int(digits[i+1]) % 2 == 0):
j = i + 1
while j < len(digits) - 1 and ((int(digits[j]) % 2 == 0 and int(digits[j+1]) % 2 == 1) or (int(digits[j]) % 2 == 1 and int(digits[j+1]) % 2 == 0)):
j += 1
substr = digits[i:j+1]
if len(substr) > max_len:
max_len = len(substr)
max_substr = substr
return max_substr
Let's test the function with the examples given in the problem statement:
print(longest_substring("225424272163254474441338664823")) # "272163254"
print(longest_substring("594127169973391692147228678476")) # "16921472"
print(longest_substring("721449827599186159274227324466")) # "7214"
The output should be:
272163254
16921472
7214