class Solution:
def modifyString(self, s: str) -> str:
"""tc O(N) sc O(N)
"""
n = len(s)
res = []
for i in range(n):
x= y = '?'
if s[i] == '?':
if i > 0:
l = i-1
x = res[l]
if i+1 < n:
r = i +1
y = s[r]
tmp = 'a'
while tmp == y or tmp == x:
tmp = chr((97+randint(0,25)%26))
res.append(tmp)
else:
res.append(s[i])
return ''.join(res)
Optimization : We do not need more than 3 letters to build a non-repeating character sequence.
class Solution:
def modifyString(self, s: str) -> str:
s = list(s)
for i in range(len(s)):
if s[i] == "?":
for c in "abc":
if (i == 0 or s[i-1] != c) and (i+1 == len(s) or s[i+1] != c):
s[i] = c
break
return "".join(s)