Sponsored
Sponsored
This approach involves inspecting characters in the string one by one and checking the last two characters of the resulting string being constructed. If three consecutive characters are found, the current character is skipped, effectively removing it. This ensures that no three consecutive identical characters are present in the resulting string.
Time Complexity: O(n)
, where n
is the length of the string, as we iterate through the string once. Space Complexity: O(n)
due to space required to generate the result string.
1def make_fancy_string(s: str) -> str:
2 result = []
3 for c in s:
4 if len(result) >= 2 and result[-1] == c and result[-2] == c:
5 continue
6 result.append(c)
7 return ''.join(result)
8
9s = "aabaa"
10print(make_fancy_string(s))
In Python, this implementation appends each character to a list and joins the list into a string at the end. It checks the last two characters of the list to determine if the current character can be appended.
This approach uses a sliding window to keep track of the count of consecutive characters. If the count reaches three, we skip adding the current character to the result. This takes advantage of window logic to efficiently manage consecutive character tracking with minimal operations.
Time Complexity: O(n)
. Space Complexity: O(n)
.
1
JavaScript uses an array and a counter to manage the characters to be retained, joining them back into a string at the end, respecting non-consecutive limits.