LeetCode 1957: Delete Characters to Make Fancy String Solution

Master LeetCode problem 1957 (Delete Characters to Make Fancy String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1957. Delete Characters to Make Fancy String

Easy

Problem Explanation

Explanation:

To make a fancy string, we need to remove characters such that no three consecutive characters are equal. We can achieve this by iterating through the string and removing characters when we encounter three consecutive equal characters. We can do this by keeping track of the current character and the count of consecutive characters seen so far. :

Solution Code

class Solution {
    public String makeFancyString(String s) {
        StringBuilder sb = new StringBuilder();
        int count = 1;
        char prev = s.charAt(0);
        sb.append(prev);
        
        for (int i = 1; i < s.length(); i++) {
            char curr = s.charAt(i);
            if (curr == prev) {
                count++;
            } else {
                count = 1;
                prev = curr;
            }
            
            if (count < 3) {
                sb.append(curr);
            }
        }
        
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1957 (Delete Characters to Make Fancy String)?

This page provides optimized solutions for LeetCode problem 1957 (Delete Characters to Make Fancy String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1957 (Delete Characters to Make Fancy String)?

The time complexity for LeetCode 1957 (Delete Characters to Make Fancy String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1957 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1957 in Java, C++, or Python.

Back to LeetCode Solutions