leetcode - 1531. String Compression II

Description

Run-length encoding is a string compression method that works by replacing consecutive identical characters (repeated 2 or more times) with the concatenation of the character and the number marking the count of the characters (length of the run). For example, to compress the string “aabccc” we replace “aa” by “a2” and replace “ccc” by “c3”. Thus the compressed string becomes “a2bc3”.

Notice that in this problem, we are not adding ‘1’ after single characters.

Given a string s and an integer k. You need to delete at most k characters from s such that the run-length encoded version of s has minimum length.

Find the minimum length of the run-length encoded version of s after deleting at most k characters.

Example 1:

Input: s = "aaabcccd", k = 2
Output: 4
Explanation: Compressing s without deleting anything will give us "a3bc3d" of length 6. Deleting any of the characters 'a' or 'c' would at most decrease the length of the compressed string to 5, for instance delete 2 'a' then we will have s = "abcccd" which compressed is abc3d. Therefore, the optimal way is to delete 'b' and 'd', then the compressed version of s will be "a3c3" of length 4.

Example 2:

Input: s = "aabbaa", k = 2
Output: 2
Explanation: If we delete both 'b' characters, the resulting compressed string would be "a4" of length 2.

Example 3:

Input: s = "aaaaaaaaaaa", k = 0
Output: 3
Explanation: Since k is zero, we cannot delete anything. The compressed string is "a11" of length 3.

Constraints:

1 <= s.length <= 100
0 <= k <= s.length
s contains only lowercase English letters.

Solution

Recursive (TLE)

Delete one character a time, and keep track of the shortest compressed string.

Time complexity: o ( n k ) o(n^k) o(nk)
Space complexity: o ( n ) o(n) o(n)

DP

Solved after help.

For a function like helper(prev_ch, prev_cnt, index, k), we have 2 options, keep the current character, or delete the current character.

If delete, then return helper(prev_ch, prev_cnt, index + 1, k - 1)
If keep, then there are 2 conditions, the current character is the same with previous one, or not.

  • If the current character is the same as the previous one, then the result will be: helper(prev_ch, prev_cnt + 1, index + 1, k). Notice when the previous cnt is 1, 9, 99, then the length would increase 1. (1->2, 9->10, 99->100)
  • If the current character is different from the previous one, then the result will be: helper(s[i], 1, index + 1, k) + 1

Use lru_cache(None) for memorization.

Time complexity: o ( 26 ∗ n ∗ n ∗ k ) o(26*n*n*k) o(26nnk)
Space complexity: o ( 26 ∗ n ∗ n ∗ k ) o(26*n*n*k) o(26nnk)

Code

Recursive (TLE)

class Solution:
    def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
        def get_compressed_string(string: str) -> str:
            prev_c = ''
            compressed_string = ''
            cnt = 0
            for ch in string:
                if ch != prev_c:
                    if prev_c:
                        if cnt > 1:
                            compressed_string += f'{prev_c}{cnt}'
                        else:
                            compressed_string += prev_c
                    prev_c = ch
                    cnt = 0
                cnt += 1
            if cnt > 1:
                compressed_string += f'{prev_c}{cnt}'
            else:
                compressed_string += prev_c
            return compressed_string

        memo = {}
        def helper(string: str, k: int) -> int:
            if (string, k) in memo:
                return memo[(string, k)]
            if k == 0:
                memo[(string, k)] = len(get_compressed_string(string))
                return memo[(string, k)]
            res = len(get_compressed_string(string))
            for i in range(len(string)):
                new_string = string[:i] + string[i + 1:]
                res = min(res, helper(new_string, k - 1))
            memo[(string, k)] = res
            return memo[(string, k)]
        return helper(s, k)

DP

class Solution:
    def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
        @lru_cache(None)
        def helper(prev_ch: str, prev_cnt: int, index: int, k: int) -> int:
            if k < 0:
                return 101
            if index == len(s):
                return 0
            # delete current character
            delete = helper(prev_ch, prev_cnt, index + 1, k - 1)
            # keep current character
            if s[index] == prev_ch:
                keep = helper(prev_ch, prev_cnt + 1, index + 1, k)
                if prev_cnt in [1, 9, 99]:
                    keep += 1
            else:
                keep = helper(s[index], 1, index + 1, k) + 1
            res = min(delete, keep)
            return res
        
        return helper('', 0, 0, k)

你可能感兴趣的:(OJ题目记录,leetcode,python,算法)