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)
.
1using System.Text;
class MakeFancyString {
static string MakeFancy(string s) {
StringBuilder result = new StringBuilder();
int count = 1;
for (int i = 0; i < s.Length; i++) {
if (i > 0 && s[i] == s[i - 1]) {
count++;
} else {
count = 1;
}
if (count < 3) {
result.Append(s[i]);
}
}
return result.ToString();
}
static void Main() {
string s = "aabaa";
Console.WriteLine(MakeFancy(s));
}
}
In C#, a counter tracks consecutive repetitions, and a StringBuilder
constructs the emerging string by respecting the maximum two repetition rule.