algoadvance

Leetcode 1957. Delete Characters to Make Fancy String

Problem Statement


Given a string s, delete the minimum number of characters from s such that no three consecutive characters are the same.

Return the final string after the deletion.

Clarifying Questions

  1. Can the string be empty or contain only one or two characters? Yes, it can.
  2. Are there any constraints on the input string? 1 <= s.length <= 10^5.
  3. If the string is already a “fancy” string, do we return it as is? Yes, return it as it is.

Strategy


Code

public class FancyString {
    public static String makeFancyString(String s) {
        StringBuilder result = new StringBuilder();
        
        for (char c : s.toCharArray()) {
            int len = result.length();
            // Check if we need to append this character or not
            if (len >= 2 && result.charAt(len - 1) == c && result.charAt(len - 2) == c) {
                continue;
            }
            result.append(c);
        }
        
        return result.toString();
    }

    public static void main(String[] args) {
        String s1 = "leeetcode";
        String s2 = "aaabaaaa";
        String s3 = "aab";
        
        System.out.println(makeFancyString(s1)); // Output: "leetcode"
        System.out.println(makeFancyString(s2)); // Output: "aabaa"
        System.out.println(makeFancyString(s3)); // Output: "aab"
    }
}

Time Complexity


This solution is efficient and should work within the constraints provided.

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI