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
In Java, using a StringBuilder
, this approach tracks consecutive characters with a count variable to control appending operations based on a threshold.