Problem Description
Given a string s consisting of lowercase English letters and the '?' character, replace every '?' with a lowercase letter such that the final string does not have any consecutive repeating characters. You must preserve the non-'?' characters and only change the '?' characters. It is guaranteed that apart from '?', the string has no consecutive repeating characters.
Key Insights
- Replace each '?' independently by trying a small set of candidate letters (e.g., 'a', 'b', 'c') to ensure that the character is different from its immediate neighbors.
- The left neighbor is already resolved when processing left-to-right; the right neighbor is taken from the original string.
- Handling consecutive '?' properly is simple by processing them one by one.
Space and Time Complexity
Time Complexity: O(n), where n is the length of string s, since we traverse the string once. Space Complexity: O(n), for constructing the resulting string.
Solution
We iterate through the string from left to right. For each character:
- If it is not a '?', simply add it to our result.
- If it is a '?', try letters 'a', 'b', and 'c' (or any set of three letters) until we find one that does not match the last character in our result (if any) and does not equal the next character (if the next character is not a '?'). By choosing a letter that satisfies both conditions, we ensure that no consecutive characters become identical. This greedy approach is sufficient due to the limited alphabet and guarantees provided by the problem.