不知道要拿来做什么但觉得很有意思的个人博客
1576. 替换所有的问号
1576. 替换所有的问号

1576. 替换所有的问号

1576. 替换所有的问号

给你一个仅包含小写英文字母和 ‘?’ 字符的字符串 s,请你将所有的 ‘?’ 转换为若干小写字母,使最终的字符串不包含任何 连续重复 的字符。

显然三个字符串已经足够。判断由于顺序是先判断左后判断右,那么右边若做了修改,即不能保证左边不一样。因此继续循环判断。

class Solution:
    def modifyString(self, s: str) -> str:
        n = len(s)
        for index, a in enumerate(s):
            if a == '?':
                a = 'a'
                while True:
                    left = False
                    right = False
                    if index > 0 and s[index - 1] == a:
                            a = chr(ord(s[index - 1]) + 1)
                            left = True
                    if index < n-1 and s[index + 1] == a:
                            a = chr(ord(s[index + 1]) + 1)
                            left = False
                            right = True
                    if not left and not right:
                        # print(a)
                        break
                    if left:
                        break
                s = s.replace("?",a,1)
                # print(s)
        return s

官方标答:
官方仅在三个字符中选取。

class Solution:
    def modifyString(self, s: str) -> str:
        res = list(s)
        n = len(res)
        for i in range(n):
            if res[i] == '?':
                for b in "abc":
                    if not (i > 0 and res[i - 1] == b or i < n - 1 and res[i + 1] == b):
                        res[i] = b
                        break
        return ''.join(res)

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/replace-all-s-to-avoid-consecutive-repeating-characters

发表评论

您的电子邮箱地址不会被公开。