Issue
Here's my function:
def remove_more_than_two_reps(text):
result = list(text)
for idx,char in enumerate(text):
if(result[:idx].count(char) > 2):
result.remove(char)
return ''.join(result)
expected result:
text = 'teeeexxxxt'
result = remove_more_than_two_reps(text)
>'teexxt'
My function just returns the original string, what is the problem?
Solution
Try using append
which is O(1)
instead of remove
which is O(n)
:
def remove_more_than_two_reps(text: str) -> str:
result = []
for ch in text:
if len(result) < 2 or result[-1] != ch or result[-2] != ch:
result.append(ch)
return ''.join(result)
text = 'teeeexxxxt'
result = remove_more_than_two_reps(text)
print(result)
Output:
teexxt
Answered By - Sash Sinha
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.