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

  1. Initialize an empty result string, result.
  2. Initialize a variable count to track the count of consecutive identical characters.
  3. Iterate through the given string s.
  4. For each character, check if it’s the same as the previous character. If yes, increment the count.
  5. If the count is less than 3, append the character to the result.
  6. If the character is different from the previous one, reset the count to 1 and append the character to the result.
  7. Return the result.

Code

Below is the code implementing the above logic:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
    def makeFancyString(self, s: str) -> str:
        # Step 1: Initialize result and count
        result = ""
        count = 1

        # Step 2: Iterate through the given string
        for i in range(1, len(s)):
            # Step 4: Check if the current character is the same as the previous one
            if s[i] == s[i - 1]:
                count += 1
            else:
                # Step 6: Reset the count if the character is different
                count = 1

            # Step 5: Append the character if the count is less than 3
            if count < 3:
                result += s[i - 1]

        # Append the last character, as it is not considered in the loop
        result += s[-1]

        # Step 7: Return the result
        return result

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.