Given a string, create a new string with all the consecutive duplicates removed.
=====================================================================
Hint: You may make a new string to store the result. You can check whether the current character and the next character are the same, then add that character to the new string.
# enter given string
str1 = input()
# add symbol that will not exist in the string,
# to process the last symbol correctly
str1 += "@"
# another string to store the result
str2 = ""
# run until last character in initial string
for i in range(len(str1) - 1):
# check whether the current character and the next character are the same
if str1[i] != str1[i + 1]:
# if not the same, add character to the new string
str2 += str1[i]
print(str2)
If the input is "abcde", the string will be "abcde@", and the last comparison will be 'e' vs '@', (which is not the same for any input), and that last symbol will be added in any case.
If the input is "abcdeee", then all previous 'e' will be ignored (they are the same), and th last one will be appended, as it is different from "@"
Comments
Leave a comment