Leetcode Problem #1957: Delete Characters to Make Fancy String
Given a string s, a fancy string is a string where no three consecutive characters are equal. Return the longest possible fancy string that can be obtained by deleting some characters from s.
s = "leeetcode"Output: "leetcode"
s = "aaabaaaa"Output: "aabaa"
s = "aab""aab"Constraints:
1 <= s.length <= 10^5s consists only of lowercase English letters.s be empty?
s is at least 1.s?
s contains only lowercase English letters.s to this list while ensuring no three consecutive characters are the same.s while simultaneously filling the resultant list based on the fancy string criterion.s[i]:
s[i].s[i] to the resultant list.s[i].Here is the implementation of the above approach:
def makeFancyString(s: str) -> str:
if len(s) < 3:
return s
result = [] # Initialize an empty list to store the resultant fancy string characters
# Iterate through the given string
for char in s:
# Check if last two characters in the result list are the same as the current character
if len(result) < 2 or not (result[-1] == char and result[-2] == char):
result.append(char) # append the current character if the condition is satisfied
return ''.join(result) # Convert list to string
# Example usage:
print(makeFancyString("leeetcode")) # Output: "leetcode"
print(makeFancyString("aaabaaaa")) # Output: "aabaa"
print(makeFancyString("aab")) # Output: "aab"
n is the length of the input string s. We iterate through the string once.By following the above methodology, we ensure the resultant string is the longest possible fancy string as required.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?