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

  1. Initialize an empty result string to store the final result.
  2. Iterate through the given string s.
  3. 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.
  4. If the character is not a ‘?’, simply append it to the result.
  5. Return the result.

Code

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def modifyString(self, s: str) -> str:
        # Step 1: Initialize the result string
        result = ""

        # Step 2: Iterate through the given string
        for i in range(len(s)):
            # Step 3a: Check if the character is a '?'
            if s[i] == '?':
                # Find a letter that doesn't match the previous or next character
                for letter in 'abc':
                    if (i == 0 or letter != result[-1]) and (i == len(s) - 1 or letter != s[i + 1]):
                        result += letter
                        break
            else:
                # Step 4: Append the non '?' character to the result
                result += s[i]

        # Step 5: Return the result
        return result

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.