Problem
You are given a string s
consisting of only lowercase English letters. In one operation, you can:
Delete the entire string
s
, orDelete the first
i
letters ofs
if the firsti
letters ofs
are equal to the followingi
letters ins
, for anyi
in 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 <= 4000
s
consists only of lowercase English letters.
Solution (Java)
class Solution {
Integer[] dp = new Integer[4001];
public int deleteString(String s) {
return helper(s, 0);
}
public int helper(String s, int idx) {
if (idx == s.length()) return 0;
if (dp[idx] != null) {
return dp[idx];
}
int answer = 1;
for (int i = idx; 2 * i <= s.length() - 2 + idx; i++) {
if (dp[i + 1] != null) continue;
int len = i - idx + 1;
if (s.substring(idx, idx + len).equals(s.substring(idx + len, idx + 2 * len))) {
answer = Math.max(answer, 1 + helper(s, i + 1));
}
}
return dp[idx] = answer;
}
}
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).