Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 1576: Replace All ?'s to Avoid Consecutive Repeating Characters

String

LeetCode 1576 Solution Explanation

Explanation:

To solve this problem, we need to iterate through the string and replace any '?' character with a lowercase letter such that there are no consecutive repeating characters. We can achieve this by checking the characters before and after the '?' to determine the valid replacements. If the character before '?' is 'a' and the character after '?' is 'b', then we can replace '?' with any letter except 'a' and 'b'. :

LeetCode 1576 Solutions in Java, C++, Python

class Solution {
    public String modifyString(String s) {
        char[] charArray = s.toCharArray();
        
        for (int i = 0; i < charArray.length; i++) {
            if (charArray[i] == '?') {
                char prev = (i == 0) ? ' ' : charArray[i - 1];
                char next = (i == charArray.length - 1) ? ' ' : charArray[i + 1];
                
                char replacement = 'a';
                while (replacement == prev || replacement == next) {
                    replacement++;
                }
                charArray[i] = replacement;
            }
        }
        
        return new String(charArray);
    }
}

Interactive Code Editor for LeetCode 1576

Improve Your LeetCode 1576 Solution

Use the editor below to refine the provided solution for LeetCode 1576. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems