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.
1public class MakeFancyString {
2 public static String makeFancyString(String s) {
3 StringBuilder result = new StringBuilder();
4 for (char c : s.toCharArray()) {
5 if (result.length() >= 2 && result.charAt(result.length() - 1) == c && result.charAt(result.length() - 2) == c) {
6 continue;
7 }
8 result.append(c);
9 }
10 return result.toString();
11 }
12
13 public static void main(String[] args) {
14 String s = "aabaa";
15 System.out.println(makeFancyString(s));
16 }
17}
This Java solution builds the output string using a StringBuilder
, checking to ensure no three consecutive identical characters by inspecting the last two characters in the builder.
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.