DEV Community

vc7
vc7

Posted on • Edited on

1

LeetCode in Swift - 1957. Delete Characters to Make Fancy String

Problem

Idea and the routine

Create a result string for use through the routine.

  • Go through and count the appearance of characters
    • If current character is NOT as same as the previous character
      • Reset count to 1
      • Append to the result string
    • If count is 1 and current character is as same as the previous character
      • Count += 1
      • Append to the result string
    • If appearance is >= 2
      • Do anything. Since the count is reaching the limit, so it's no meaning to add 1 to it when there is no additional purpose or requirement.

Code

class Solution {
    func makeFancyString(_ s: String) -> String {
        var string = ""
        /// Init with 0 as a placeholder
        var previous: Character = "0"
        var count = 0

        for c in s {
            if c != previous {
                previous = c
                count = 1
                string.append(c)
            } else if count < 2 {
                string.append(c)
                count += 1
            }
        }
        return string
    }
}
Enter fullscreen mode Exit fullscreen mode

Complexity

n as length of the given string s

  • Time Complexity: O(n)
    • Linear traversal
  • Space Complexity: O(n)
    • Copying to a new string as the same length at the worst case.

In place and two flags

Next time.

Runtime Note

I tried to use var characters: [Character] and return String(result), in the end I using string directly because as result this way is faster as LeetCode perspective.

End of the post

That's it!

Please leave comment if you have any comments, thanks for your reading!

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay