Leetcode 1576. Replace All ?’s to Avoid Consecutive Repeating Characters
Given a string s
containing only lowercase English letters and the '?'
character, you need to replace every '?'
character with a lowercase English letter so that the final string does not contain any consecutive repeating characters. You can assume that the given string is not too long and that it is always possible to replace the '?'
character to achieve the desired outcome.
s
be empty? Answer: Yes, it can be. An empty string should return as it is.s
? Answer: It can be reasonably long, but we won’t specify exact limits here as the problem assumes it won’t be too long.'?'
is found, choose a replacement character.'?'
encountered, choose a character from ‘a’ to ‘z’ ensuring it doesn’t create a repeating sequence.'?'
characters correctly by processing them from left to right.public class ReplaceQuestionMarks {
public static String modifyString(String s) {
char[] charArray = s.toCharArray();
int n = charArray.length;
for (int i = 0; i < n; i++) {
if (charArray[i] == '?') {
for (char replacement = 'a'; replacement <= 'z'; replacement++) {
if ((i > 0 && charArray[i - 1] == replacement) || (i < n - 1 && charArray[i + 1] == replacement)) {
continue;
}
charArray[i] = replacement;
break;
}
}
}
return new String(charArray);
}
public static void main(String[] args) {
// Example test cases
System.out.println(modifyString("ab?ac")); // Sample input
System.out.println(modifyString("??ywz")); // Sample input
System.out.println(modifyString("a?b?c")); // Sample input
}
}
s
. This is because we only make a single pass through the string and each character replacement operation takes constant time.s
. This is due to storing the character array and eventually converting it back to a string.By following this approach, we ensure that we do not introduce any consecutive repeating characters while replacing all '?'
characters.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?