Input: s ="leeetcode"Output: "leetcode"Explanation:
Remove an 'e' from the first group of 'e's to create "leetcode".No three consecutive characters are equal, so return"leetcode".
Example 2:
1
2
3
4
5
6
Input: s ="aaabaaaa"Output: "aabaa"Explanation:
Remove an 'a' from the first group of 'a's to create "aabaaaa".Remove two 'a's from the second group of 'a's to create "aabaa".No three consecutive characters are equal, so return"aabaa".
Example 3:
1
2
3
Input: s ="aab"Output: "aab"Explanation: No three consecutive characters are equal, so return"aab".
The problem requires us to limit each character to appear at most twice consecutively. To achieve this, we can keep a count (cnt) of how many times the current character has appeared consecutively so far. This count lets us decide if the next character should be added or skipped.
Here is the approach:
Tracking consecutive characters: By starting with the first character of the input string s and iterating through the rest, we can build the result string (ans) one character at a time. This incremental approach allows us to check each character as it arrives, only adding it if it maintains the “fancy” requirement of no three consecutive identical characters.
Switching Between Characters: Whenever a new character (different from the previous one) is encountered, the consecutive count (cnt) is reset, allowing us to add the new character freely. This reset is crucial because a different character means there’s no longer a risk of exceeding two consecutive characters.
classSolution:
defmakeFancyString(self, s: str) -> str:
# List to store the final result ans = []
# Append the first character ans.append(s[0])
# Initialize the counter cnt =1# Iterate through the string starting from the second characterfor i in range(1, len(s)):
if s[i] == ans[-1]:
# If current character matches last character in result, increment the counter cnt +=1if cnt <3:
# Only add the character if the count is less than 3 ans.append(s[i])
else:
# If current character is different, reset the counter and add the character cnt =1 ans.append(s[i])
# Join the list into a string and returnreturn''.join(ans)