Delete Characters to Make Fancy String
Let’s tackle the problem by writing a function that iterates through the given string s
and builds a new string that ensures no three consecutive characters are the same.
Steps
- Initialize an empty result string,
result
. - Initialize a variable
count
to track the count of consecutive identical characters. - Iterate through the given string
s
. - For each character, check if it’s the same as the previous character. If yes, increment the
count
. - If the
count
is less than 3, append the character to theresult
. - If the character is different from the previous one, reset the
count
to 1 and append the character to theresult
. - Return the
result
.
Code
Below is the code implementing the above logic:
|
|
Explanation
The code ensures that no three consecutive characters in the string are the same by tracking the count of consecutive identical characters and adding them to the result only if the count is less than 3.