zoukankan      html  css  js  c++  java
  • 【leetcode】1576. Replace All ?'s to Avoid Consecutive Repeating Characters

    题目如下:

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

    解题思路:题目不难,只要把?替换成与前面和后面的字符都不一致的字符即可,注意要考虑?在字符首尾出现的情况。

    代码如下:

    class Solution(object):
        def modifyString(self, s):
            """
            :type s: str
            :rtype: str
            """
            res = ''
            char_list = [chr(i) for i in range(97,123)]
            for i in range(len(s)):
                if s[i] != '?':
                    res += s[i]
                    continue
                elif len(s) == 1:
                    res += 'a'
                elif i == len(s) - 1:
                    for char in char_list:
                        if char != res[-1]:
                            res += char
                            break
                elif i == 0:
                    for char in char_list:
                        if char != s[i+1]:
                            res += char
                            break
                else:
                    for char in char_list:
                        if char != s[i+1] and char != res[-1]:
                            res += char
                            break
    
            return res
  • 相关阅读:
    TP框架中模板赋值
    使用PHP和GZip压缩网站JS/CSS文件加速网站访问速度
    测试相关知识分享(百度和其他途径查找到的)
    测试基本概念
    shell编程之重定向
    shell编程之函数
    shell编程之循环
    shell编程之测试和判断
    shell编程之变量
    Linux系统学习之正则表达式
  • 原文地址:https://www.cnblogs.com/seyjs/p/13999892.html
Copyright © 2011-2022 走看看