DDSA Solutions

1957. Delete Characters to Make Fancy String

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

Problem Overview

Delete Characters to Make Fancy String (Unknown) asks you to solve a structured algorithmic task. This is a common String / Greedy pattern in coding interviews. Build result StringBuilder; skip appending char if last two are already the same.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

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

Related patterns: String, Greedy

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();
    }
}
Was this solution helpful?

Related Problems