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.
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4
5char* makeFancyString(char* s) {
6 size_t len = strlen(s);
7 char* result = (char*)malloc(len + 1);
8 int index = 0;
9
10 for (int i = 0; i < len; i++) {
11 if (index >= 2 && result[index - 1] == s[i] && result[index - 2] == s[i]) {
12 continue;
13 }
14 result[index++] = s[i];
15 }
16 result[index] = '\0';
17 return result;
18}
19
20int main() {
21 char s[] = "aabaa";
22 char* result = makeFancyString(s);
23 printf("%s", result);
24 free(result);
25 return 0;
26}
Each character of the input string is added to a new string, checking if it should be added by comparing with the last two characters of the newly created string. This avoids three consecutive repetitions. Memory is manually managed in C using malloc
and free
.
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
This C implementation uses a counter to track the number of consecutive identical characters. Every time a character is added, it checks if the three consecutive rule is broken, allowing only up to two identical characters consecutively.