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.
1function makeFancyString(s) {
2 let result = [];
3 for (let i = 0; i < s.length; i++) {
4 if (result.length >= 2 && result[result.length - 1] === s[i] && result[result.length - 2] === s[i]) {
5 continue;
6 }
7 result.push(s[i]);
8 }
9 return result.join('');
10}
11
12let s = "aabaa";
13console.log(makeFancyString(s));
In JavaScript, this solution builds a result array and checks the last two elements before pushing a new character to ensure no three identical consecutive characters. The final result is constructed by joining the array elements.
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.