DDSA Solutions

1957. Delete Characters to Make Fancy String

Time: O(n)
Space: O(n)
Advertisement

Approach

Build result StringBuilder; skip appending char if last two are already the same.

Key Techniques

String

String problems range from simple character counting to complex pattern matching. Common approaches include two pointers, sliding window, prefix hashing, and the KMP algorithm. In C#, strings are immutable — use StringBuilder for efficient concatenation inside loops.

Greedy

Greedy algorithms make locally optimal choices at each step, hoping to reach a global optimum. Greedy works when a problem has the "greedy choice property" and "optimal substructure". Common applications: interval scheduling, activity selection, Huffman coding, and jump game.

1957.cs
C#
// Approach: Build result StringBuilder; skip appending char if last two are already the same.
// Time: O(n) Space: O(n)

public class Solution
{
    public string MakeFancyString(string s)
    {
        StringBuilder sb = new StringBuilder();
        foreach (char c in s)
        {
            if (sb.Length < 2 ||
                sb[sb.Length - 1] != c || sb[sb.Length - 2] != c)
                sb.Append(c);
        }
        return sb.ToString();
    }
}
Advertisement
Was this solution helpful?