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.
1#include <iostream>
2#include <string>
3
4std::string makeFancyString(const std::string& s) {
5 std::string result;
6 for (char c : s) {
7 if (result.size() >= 2 && result[result.size() - 1] == c && result[result.size() - 2] == c) {
8 continue;
9 }
10 result += c;
11 }
12 return result;
13}
14
15int main() {
16 std::string s = "aabaa";
17 std::cout << makeFancyString(s) << std::endl;
18 return 0;
19}
This C++ solution uses the std::string
class to dynamically build a new string. It checks the last two characters to ensure they don't repeat with the current character.
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.