Skip to main content
Back to problems
#1576
Easy Algorithms

Replace all s to avoid consecutive repeating characters

String
45.2% acceptance
Feb 25, 2026
603
181
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.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn modify_string(s: String) -> String {
    let mut chars: Vec<char> = s.chars().collect();
    let n = chars.len();
    for i in 0..n {
      if chars[i] == '?' {
        for c in b'a'..=b'z' {
          let c = c as char;
          let left_ok = i == 0 || chars[i - 1] != c;
          let right_ok = i + 1 == n || chars[i + 1] != c;
          if left_ok && right_ok {
            chars[i] = c;
            break;
          }
        }
      }
    }
    chars.iter().collect()
  }
}