Replace All ?'s to Avoid Consecutive Repeating Characters
You are given a string with lowercase English letters and ‘?’ characters. Your task is to replace the ‘?’ characters in such a way that no consecutive characters are the same.
Steps
- Initialize an empty result string to store the final result.
- Iterate through the given string
s
. - For each character, check if it’s a ‘?’. a. If it’s a ‘?’, find a lowercase letter that is not equal to the previous or next character in the original string. b. Append the found letter to the result.
- If the character is not a ‘?’, simply append it to the result.
- Return the result.
Code
Here’s the code:
|
|
Explanation
The code takes care of the constraint that no two consecutive characters should be the same by carefully selecting the replacement for the ‘?’ character. By considering the characters just before and after the ‘?’, we can ensure that we select a letter that doesn’t create any repeating characters. The logic uses a simple loop through the letters ‘a’, ‘b’, and ‘c’ to find a suitable replacement, and since there are no consecutive repeating characters in the input, there is always a valid letter to choose.