Leetcode 1576. Replace All ?’s to Avoid Consecutive Repeating Characters
You are given a string s
that contains only lowercase English letters and '?'
characters. You need to replace all '?'
characters in the string such that no two adjacent characters are the same. There may be multiple valid solutions, return any one of them.
?
characters?
'?'
, replace it with a character that doesn’t match the previous or next character to avoid consecutive repeating characters.#include <iostream>
#include <string>
std::string modifyString(std::string s) {
int n = s.length();
for (int i = 0; i < n; i++) {
if (s[i] == '?') {
for (char ch = 'a'; ch <= 'c'; ch++) {
if ((i > 0 && s[i-1] == ch) || (i < n - 1 && s[i+1] == ch)) {
continue;
} else {
s[i] = ch;
break;
}
}
}
}
return s;
}
int main() {
std::string s = "?zs";
std::cout << "Modified string: " << modifyString(s) << std::endl;
return 0;
}
s
.'?'
, we attempt to replace it with characters ‘a’, ‘b’, or ‘c’.s[i-1]
) or the next character (s[i+1]
). If it does not, we replace the '?'
with this character.n
is the length of the input string. We pass through the string once and perform constant-time operations for each character.This algorithm should efficiently replace all occurrences of '?'
with characters that ensure no consecutive characters are the same.
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?