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
  • 相关阅读:
    C/C++知识点收集
    JAVA相关知识点理解
    Windows相关收集
    【原创】java的反射机制
    【原创】如何配置声明书事务
    【原创】spring中的事务传播特性
    【摘录】JAVA内存管理-自动选择垃圾收集器算法
    【摘录】JAVA内存管理-JVM垃圾收集机制
    【摘录】数据库拆分的一般方法和原则
    【摘录】JAVA内存管理-有关垃圾收集的关键参数
  • 原文地址:https://www.cnblogs.com/seyjs/p/13999892.html
Copyright © 2011-2022 走看看