Replace All ? to Avoid Consecutive Repeating Characters - String - Easy - LeetCode
💻 coding

Replace All ? to Avoid Consecutive Repeating Characters - String - Easy - LeetCode

1 min read 277 words
1 min read
ShareWhatsAppPost on X
  • 1The task is to replace '?' characters in a string to avoid consecutive repeating characters.
  • 2The solution guarantees that any valid string can be formed given the constraints.
  • 3The algorithm operates with a time complexity of O(n) and space complexity of O(n).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"The task is to replace '?' characters in a string to avoid consecutive repeating characters."

Replace All ? to Avoid Consecutive Repeating Characters - String - Easy - LeetCode

Given a string s containing only lower case English letters and the '?' character, convert all the '?' characters into lower case 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. It can be shown that an answer is always possible with the given constraints.

Example 1:

Input: s = "?zs" Output: "azs" Explanation: There are 25 solutions for this problem. From "azs" to "yzs", all are valid. Only "z" is an invalid modification as the string will consist of consecutive repeating characters in "zzs". Example 2:

Input: s = "ubv?w" Output: "ubvaw" Explanation: There are 24 solutions for this problem. Only "v" and "w" are invalid modifications as the strings will consist of consecutive repeating characters in "ubvvw" and "ubvww". Example 3:

Input: s = "j?qg??b" Output: "jaqgacb" Example 4:

Input: s = "??yw?ipkj?" Output: "acywaipkja"

Constraints:

1 <= s.length <= 100

s contains only lower case English letters and '?'.

public class Solution {
 public string ModifyString(string s) { 
 if(s.Length == 0){
 return "";
 }
 
 if(s.Length==1){
 return s[0]=='?'?"a":s;
 }
 var arr = s.ToCharArray();
 for(int i=0;i<arr.Length;i++){
 if(arr[i]=='?'){
 if(i==0){
 if(arr[i+1]=='a'){
 arr[i]='b';
 }
 else{
 arr[i]='a';
 }
 }
 else if(i==arr.Length-1){
 if(arr[i-1]=='a'){
 arr[i]='b';
 }
 else{
 arr[i]='a';
 }
 }
 else{
 if(arr[i-1]=='a' || arr[i+1]=='a'){
 if(arr[i-1]=='b' || arr[i+1]=='b'){
 arr[i]='c';
 }
 else{
 arr[i]='b';
 }
 }
 else{
 arr[i]='a';
 }
 }
 } 
 }
 
 return new string(arr);
 }
}

Time Complexity: O(n)

Space Complexity: O(n)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 2 October 2020 · 1 min read · 277 words

Part of AskGif Blog · coding

You might also like