假设我们有一个只包含字母和“?”的小写字符串 s。字符,我们必须转换所有 '?' 字符转换成小写字母,这样最终的字符串将不会有任何连续的重复字符。如果有多个解决方案,请返回其中任何一个。
所以,如果输入像 s = "hel??",那么输出将是 helab,se 第一个问号可能是除 'l' 之外的任何东西,当给出第一个时,第二个可以是除 'a' 之外的任何东西.
让我们看看以下实现以获得更好的理解 -
def solve(s): if len(s) == 1 : if s == "?": return "a" return s s = list(s) for i in range(len(s)): if s[i] == "?": if i == 0 and s[i+1] == "?": s[i] = "a" elif i == 0 and s[i+1] == "a": s[i] = "b" elif i == 0: s[i] = "a" elif i == len(s)-1 and s[i-1] == "a": s[i] = "b" elif i == len(s)-1: s[i] = "a" elif s[i-1] == "a" and s[i+1] == "?": s[i] = "b" elif s[i+1] == "?": s[i] = "a" elif (s[i-1] == "a" and s[i+1] == "b") or (s[i-1] == "b" and s[i+1] == "a"): s[i] = "c" elif "a" in (s[i-1],s[i+1]): s[i] = "b" else: s[i] = "a" return "".join(s) s = "hel??" print(solve(s))
"hel??"输出结果
helab