You are given a string s
that contains only lowercase English letters and the '?'
character. The '?'
character can be replaced by any lowercase English letter. Replace all the '?'
characters such that the final string does not contain any consecutive repeating characters. You must return the final string. If there are multiple solutions, you may return any of them. It is guaranteed an answer exists.
s
?
'?'
.s
to a list of characters to allow mutation.'?'
found:
'?'
is at the start or end.def modifyString(s: str) -> str:
n = len(s)
s_list = list(s)
for i in range(n):
if s_list[i] == '?':
for ch in 'abcdefghijklmnopqrstuvwxyz':
if (i > 0 and s_list[i-1] == ch) or (i < n-1 and s_list[i+1] == ch):
continue
s_list[i] = ch
break
return ''.join(s_list)
# Example Usage
print(modifyString("??yw?ipkj?"))
Time Complexity: (O(n \cdot k)), where (n) is the length of the string and (k) is a constant 26 (number of lowercase English letters). This results in approximately (O(n)) since (k) is a small constant.
Space Complexity: (O(n)) for constructing the list from the string and then converting it back to a string.
This approach ensures that all questioned characters are replaced by an appropriate letter while guaranteeing no consecutive repeating characters and satisfying the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?