Skip to content

Latest commit

 

History

History
96 lines (85 loc) · 2.79 KB

1576. Replace All x's to Avoid Consecutive Repeating Characters.md

File metadata and controls

96 lines (85 loc) · 2.79 KB

the first one in Weekly Contest 205.


Difficulty : Easy

Related Topics : String


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 '?'.

Solution

  • mine
    • Java
      • Runtime: 0 ms, faster than 100.00%, Memory Usage: 37.2 MB, less than 87.62% of Java online submissions
        // O(N)time
        // O(N)space
        public String modifyString(String s) {
            char[] arr = s.toCharArray();
            int n = arr.length;
            for(int i = 0; i < n; i++){
                if(arr[i] == '?'){
                    if(i > 0){
                        if(i + 1 < n){
                            arr[i] = getChar(arr[i - 1],arr[i + 1]);
                        }else{
                            arr[i] = getChar(arr[i - 1],arr[i - 1]);
                        }
                    }else{
                        if(i + 1 < n){
                            arr[i] = getChar(arr[i + 1],arr[i + 1]);
                        }else{
                            arr[i] = 'a';
                        }
                    }
                }
            }
            return new String(arr);
        }
        
        char getChar(char a, char b){
            for(char i = 'a'; i <= 'z'; i++){
                if(i != a && i != b){
                    return i;
                }
            }
            return 0;
        }