1957. Delete Characters to Make Fancy String
UnknownView on LeetCode
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.
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
- 11. Container With Most Water(Medium)
- 12. Integer to Roman(Medium)
- 13. Roman to Integer(Easy)
- 14. Longest Common Prefix(Easy)
- 22. Generate Parentheses(Medium)
- 30. Substring with Concatenation of All Words(Hard)