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#2.0技术探讨(1):匿名方法
    C#测试类的嵌套
    介绍几款博客发布工具,绝对好用
    HttpModule,对ASP.NET的事件处理进行过滤,干预
    C#中,控制台模式可以使用定时器吗?
    const常量和static静态只读变量有何区别
    C#设计模式(2):工厂模式
    ASP.NET 的数据绑定语法
    DataAdapter数据集DataSet和数据库的同步(2):使用DataAdapter来更新数据集
    TCP编程(5):服务器端 TcpListener
  • 原文地址:https://www.cnblogs.com/seyjs/p/13999892.html
Copyright © 2011-2022 走看看