LeetCode 2430: Maximum Deletions on a String
Problem Description
Explanation
To solve this problem, we can iterate through the string and keep track of the longest prefix that can be deleted in each step. We can use a dynamic programming approach to store the longest prefix that matches the suffix starting from each index. Then, we can iterate through the string and update the maximum number of operations needed based on the longest prefix that can be deleted at each index.
The time complexity of this solution is O(n^2) where n is the length of the input string s, and the space complexity is O(n).
Solutions
class Solution {
public int maximumDeletions(String s) {
int n = s.length();
int[] dp = new int[n];
for (int i = 1; i < n; i++) {
int j = dp[i - 1];
while (j > 0 && s.charAt(i) != s.charAt(j)) {
j = dp[j - 1];
}
dp[i] = j + (s.charAt(i) == s.charAt(j) ? 1 : 0);
}
return n - dp[n - 1];
}
}
Loading editor...