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.
1using System;
2using System.Text;
3
4class MakeFancyString {
5 static string MakeFancy(string s) {
6 StringBuilder result = new StringBuilder();
7 foreach (char c in s) {
8 if (result.Length >= 2 && result[result.Length - 1] == c && result[result.Length - 2] == c) {
9 continue;
10 }
11 result.Append(c);
12 }
13 return result.ToString();
14 }
15
16 static void Main() {
17 string s = "aabaa";
18 Console.WriteLine(MakeFancy(s));
19 }
20}
This C# solution uses a StringBuilder
to efficiently append characters while checking the previous two characters to avoid three consecutive identical letters.
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#include <string>
std::string makeFancyString(const std::string& s) {
std::string result;
int count = 1;
for (size_t i = 0; i < s.length(); ++i) {
if (i > 0 && s[i] == s[i - 1]) {
count++;
} else {
count = 1;
}
if (count < 3) {
result += s[i];
}
}
return result;
}
int main() {
std::string s = "aabaa";
std::cout << makeFancyString(s) << std::endl;
return 0;
}
This C++ solution works like its C counterpart, using a counter to determine the number of identical consecutive characters, adjusting the logic to avoid excess duplicates.