Tuesday, March 2, 2021

[Microsoft Question][LeetCode] Replace All ?'s to Avoid Consecutive Repeating Characters

Problem: 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:

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".
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".
Input: s = "j?qg??b"
Output: "jaqgacb"
Input: s = "??yw?ipkj?"
Output: "acywaipkja"


Approach: Nothing to explain here as it is a straight forward problem to solve. Have a look at implementation directly to understand the solution.


Implementation in C#:

    public string ModifyString(string s) 

    {

        if (s?.Length == 0)

        {

            return s;

        }

        if (s.Length == 1)

        {

            return s[0] != '?' ? s : "a";

        }

        char[] sArr = s.ToCharArray();

        for (int i = 0; i < sArr.Length; ++i)

        {

            if (sArr[i] == '?')

            {

                char targetChar = 'a';

                if (i > 0 && i < sArr.Length - 1)

                {

                    targetChar = sArr[i - 1] == 'z' || sArr[i - 1] == '?' ? 'a' : (char)(sArr[i - 1] + 1);

                    if (targetChar == sArr[i + 1])

                    {

                        targetChar = targetChar == 'z' ? 'a' : (char)(targetChar + 1);

                    }

                }

                else if (i == 0)

                {

                    targetChar = sArr[i + 1] == 'z' || sArr[i + 1] == '?' ? 'a' : (char)(sArr[i + 1] + 1);

                }

                else if (i == sArr.Length - 1)

                {

                    targetChar = sArr[i - 1] == 'z' || sArr[i - 1] == '?' ? 'a' : (char)(sArr[i - 1] + 1);

                }

                sArr[i] = targetChar;

            }

        }

        return new string(sArr);

    }


Complexity: O(n)

No comments:

Post a Comment