Maximum Deletions on a String Problem
Description
LeetCode Problem 2430.
You are given a string s consisting of only lowercase English letters. In one operation, you can:
- Delete the entire string
s, or - Delete the first
iletters ofsif the firstiletters ofsare equal to the followingiletters ins, for anyiin the range1 <= i <= s.length / 2.
For example, if s = "ababc", then in one operation, you could delete the first two letters of s to get "abc", since the first two letters of s and the following two letters of s are both equal to "ab".
Return the maximum number of operations needed to delete all of s.
Example 1:
Input: s = "abcabcdabc"
Output: 2
Explanation:
- Delete the first 3 letters ("abc") since the next 3 letters are equal. Now, s = "abcdabc".
- Delete all the letters.
We used 2 operations so return 2. It can be proven that 2 is the maximum number of operations needed.
Note that in the second operation we cannot delete "abc" again because the next occurrence of "abc" does not happen in the next 3 letters.
Example 2:
Input: s = "aaabaab"
Output: 4
Explanation:
- Delete the first letter ("a") since the next letter is equal. Now, s = "aabaab".
- Delete the first 3 letters ("aab") since the next 3 letters are equal. Now, s = "aab".
- Delete the first letter ("a") since the next letter is equal. Now, s = "ab".
- Delete all the letters.
We used 4 operations so return 4. It can be proven that 4 is the maximum number of operations needed.
Example 3:
Input: s = "aaaaa"
Output: 5
Explanation: In each operation, we can delete the first letter of s.
Constraints:
1 <= s.length <= 4000sconsists only of lowercase English letters.
Solution
Approach: Memoization Search
Let dfs(i) be the maximum number of operations that delete all of s[i..]; the answer is dfs(0). If i is the end of the string, it is 0. Otherwise, for each length j with 1 <= j <= (n - i) / 2, if s[i..i+j) equals s[i+j..i+2j) we can delete the first block and get 1 + dfs(i + j); take the best over all j (a single deletion of the whole rest is always possible, so the value is at least 1).
To compare the two blocks in O(1), precompute g[i][j], the length of the longest common prefix of s[i..] and s[j..]. The blocks are equal exactly when g[i][i+j] >= j. Memoize dfs in an array f.
Complexity: The time complexity is O(n^2) and the space complexity is O(n^2), where n is the length of s.
from functools import lru_cache
class Solution:
def deleteString(self, s: str) -> int:
@lru_cache(None)
def dfs(i: int) -> int:
if i == n:
return 0
ans = 1
for j in range(1, (n - i) // 2 + 1):
if s[i : i + j] == s[i + j : i + j + j]:
ans = max(ans, 1 + dfs(i + j))
return ans
n = len(s)
return dfs(0)