LeetCode Entry

1957. Delete Characters to Make Fancy String

01.11.2024 easy 2024 kotlin rust

Filter 3+ repeating chars from string

1957. Delete Characters to Make Fancy String easy blog post substack youtube deep-dive 1.webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/787

Problem TLDR

Filter 3+ repeating chars from string #easy

Intuition

Several ways to do this: counter, comparing two previous with current, regex, two pointers (and maybe simd and pattern matching idk)

Approach

  • let’s do some golf
  • regex is slow

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(n)\), or O(1) for in-place where language permits

Code


    fun makeFancyString(s: String) =
        s.filterIndexed { i, c ->
            i < 2 || c != s[i - 1] || c != s[i - 2]
        }


    pub fn make_fancy_string(mut s: String) -> String {
        let (mut cnt, mut prev) = (0, '.');
        s.retain(|c| {
            if c == prev { cnt += 1 } else { cnt = 1 }
            prev = c; cnt < 3
        }); s
    }


    string makeFancyString(string s) {
        return regex_replace(s, regex("(.)\\1\\1+"), "$1$1");
    }