DEV Community

vc7
vc7

Posted on • Edited on

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!

Top comments (0)