Delete Characters to Make Fancy String — LeetCode 1957 Python Solution
- Problem
- #1957
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
A fancy string is a string where no three consecutive characters are equal. Given a string s, delete the minimum possible number of characters from s to make it fancy.
Example
- Input
- s = "leeetcode"
- Output
- "leetcode"
- Explanation
- Remove an 'e' from the first group of 'e's to create "leetcode".
Python solution
class Solution:
def makeFancyString(self, s: str) -> str:
ans = []
for i, c in enumerate(s):
if i < 2 or c != s[i - 1] or c != s[i - 2]:
ans.append(c)
return "".join(ans)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the string s |
| Space | O(1) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 1957. Delete Characters to Make Fancy String is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1957. Delete Characters to Make Fancy String?
- LeetCode 1957. Delete Characters to Make Fancy String is rated Easy on LeetCode.
- What is the time complexity of LeetCode 1957. Delete Characters to Make Fancy String?
- The Python solution on this page runs in O(n), where n is the length of the string s.
- What is the space complexity of LeetCode 1957. Delete Characters to Make Fancy String?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1957. Delete Characters to Make Fancy String cover?
- LeetCode 1957. Delete Characters to Make Fancy String is tagged String on LeetCode.