-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathminOperations_palindromic.java
More file actions
29 lines (22 loc) · 943 Bytes
/
minOperations_palindromic.java
File metadata and controls
29 lines (22 loc) · 943 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public class minOperations_palindromic {
// length of lps is inversely proportional to no of deletions / insertions
public int minInsertions(String s) {
return s.length() - longestPalindromeSubseq(s );
}
public int longestPalindromeSubseq(String s) {
// this is basically lcs between the string and the reverse of the string.
String reverse = new StringBuilder(s).reverse().toString();
int m = s.length();
int[][] dp = new int[m + 1][m + 1];
for(int i = 1; i <= m; i++){
for(int j = 1; j <= m; j++){
if(s.charAt(i - 1) == reverse.charAt(j - 1)){
dp[i][j] = 1 + dp[i - 1][j - 1];
} else {
dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[m][m];
}
}