Given a string s
. In one step you can insert any character at any index of the string.
Return the minimum number of steps to make s
palindrome.
A Palindrome String is one that reads the same backward as well as forward.
Example 1:
Input: s = "zzazz"
Output: 0
Explanation: The string "zzazz" is already palindrome we don't need any insertions.
Example 2:
Input: s = "mbadm"
Output: 2
Explanation: String can be "mbdadbm" or "mdbabdm".
Example 3:
Input: s = "leetcode"
Output: 5
Explanation: Inserting 5 characters the string becomes "leetcodocteel".
Example 4:
Input: s = "g"
Output: 0
Example 5:
Input: s = "no"
Output: 1
Constraints:
1 <= s.length <= 500
- All characters of
s
are lower case English letters.
思路:dp,記憶化搜索,兩頭相等,啥也不用做,往中間走,兩頭不等,那麼就是子問題,1 + min(循環遞歸),然後用cache保存中間結果. Time: O(n ^2); space(n^2);
class Solution {
public int minInsertions(String s) {
int n = s.length();
Integer[][] cache = new Integer[n + 1][n + 1];
return dfs(s, 0, n - 1, cache);
}
public int dfs(String s, int start, int end, Integer[][] cache) {
if(start >= end) {
return 0;
}
if(cache[start][end] != null) {
return cache[start][end];
}
int res = 0;
if(s.charAt(start) == s.charAt(end)) {
res = dfs(s, start + 1, end - 1, cache);
} else {
res = 1 + Math.min(dfs(s, start + 1, end, cache), dfs(s, start, end - 1, cache));
}
cache[start][end] = res;
return cache[start][end];
}
}
思路:bottom up; 記住,len是從2開始的;
class Solution {
public int minInsertions(String s) {
int n = s.length();
int[][] dp = new int[n][n];
for(int len = 2; len <= n; len++) {
for(int i = 0; i + len - 1 < n; i++) {
int j = i + len - 1;
if(s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1];
} else {
// s.charAt(i) != s.charAt(j);
dp[i][j] = 1 + Math.min(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
}