1957. Delete Characters to Make Fancy String LeetCode Solution
In this guide, you will get 1957. Delete Characters to Make Fancy String LeetCode Solution with the best time and space complexity. The solution to Delete Characters to Make Fancy String problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Delete Characters to Make Fancy String solution in C++
- Delete Characters to Make Fancy String solution in Java
- Delete Characters to Make Fancy String solution in Python
- Additional Resources
Problem Statement of Delete Characters to Make Fancy String
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.
Return the final string after the deletion. It can be shown that the answer will always be unique.
Example 1:
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:
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:
Input: s = “aab”
Output: “aab”
Explanation: No three consecutive characters are equal, so return “aab”.
Constraints:
1 <= s.length <= 105
s consists only of lowercase English letters.
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
1957. Delete Characters to Make Fancy String LeetCode Solution in C++
class Solution {
public:
string makeFancyString(string s) {
string ans;
for (const char c : s)
if (ans.length() < 2 || ans.back() != c || ans[ans.size() - 2] != c)
ans.push_back(c);
return ans;
}
};
/* code provided by PROGIEZ */
1957. Delete Characters to Make Fancy String LeetCode Solution in Java
class Solution {
public String makeFancyString(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray())
if (sb.length() < 2 || //
sb.charAt(sb.length() - 1) != c || sb.charAt(sb.length() - 2) != c)
sb.append(c);
return sb.toString();
}
}
// code provided by PROGIEZ
1957. Delete Characters to Make Fancy String LeetCode Solution in Python
class Solution:
def makeFancyString(self, s: str) -> str:
ans = []
for c in s:
if len(ans) < 2 or ans[-1] != c or ans[-2] != c:
ans.append(c)
return ''.join(ans)
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.