Replace All 's to Avoid Consecutive Repeating Characters Problem
Description
LeetCode Problem 1576.
Given a string s containing only lowercase English letters and the '?' character, convert all the '?' characters into lowercase letters such that the final string does not contain any consecutive repeating characters. You cannot modify the non '?' characters.
It is guaranteed that there are no consecutive repeating characters in the given string except for '?'.
Return the final string after all the conversions (possibly zero) have been made. If there is more than one solution, return any of them. It can be shown that an answer is always possible with the given constraints.
Example 1:
Input: s = "?zs"
Output: "azs"
Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs".
Example 2:
Input: s = "ubv?w"
Output: "ubvaw"
Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww".
Constraints:
1 <= s.length <= 100sconsist of lowercase English letters and'?'.
Solution
Approach: Greedy With Three Letters
A '?' only has to differ from its two neighbors, so among any three letters at least one is always free. Go from left to right, and for each '?' pick the first of 'a', 'b', 'c' that is equal to neither the character before it nor the character after it.
Going left to right matters: by the time we reach position i, the left neighbor is already a real letter. The right neighbor may still be a '?', which equals none of the letters, so it never blocks a choice; it will be filled next and will avoid whatever we picked here. Letters that were in the input are never changed, and the input guarantees they are not equal to each other when adjacent.
Any valid answer is accepted, so this may return a different string than the examples (for "?zs" it returns "azs", and for "ubv?w" it returns "ubvaw").
Complexity: O(n) time, since each '?' tries at most three letters, and O(n) extra space for the character array (O(1) beyond the output).
class Solution:
def modifyString(self, s: str) -> str:
chars = list(s)
n = len(chars)
for i in range(n):
if chars[i] == '?':
# a cell has only two neighbors, so one of three letters always fits
for c in 'abc':
if (i > 0 and chars[i - 1] == c) or (i + 1 < n and chars[i + 1] == c):
continue
chars[i] = c
break
return ''.join(chars)