In this post, we will see how to resolve Replace two adjacent duplicate characters in string with the next character in alphabet
Question:
I want to write a function, that will find the first occurrence of two adjacent characters that are the same, replace them with a single character that is next in the alphabet and go over the string until there are no duplicates left. In case of “zz” it should go in a circular fashion back to “a”. The string can only include characters a-z, that is, no capital letters or non-alphabetical characters. I have written a function that does it, but it is not effective enough for a very long string.s = 'aabbbc'
the function should work like aabbbc –> bbbbc –> cbbc –> ccc and finally return dc. How can I make it more efficient?Edit: for example if
s = 'ab'*10**4 + 'cc'*10**4 + 'dd'*10**4
this function is taking a lot of time.Best Answer:
As a trivial optimisation: instead of the hard reseti = 1
, you can use a softer reset i = i-1
. Indeed, if there was no duplicate between 1 and i before the transformation, then there still won’t be any duplicate between 1 and i-1 after the transformation.If you have better answer, please add a comment about this, thank you!
Source: Stackoverflow.com