ex. abb->abba, dabbde->edabbade
思路:一道DP题,设A[i][j]表示把s从位置i到位置j变成palindrome,则有:如果两头相等s[i] = s[j],那么A[i][j] = A[i+1][j-1]。如果两头不等,那么A[i][j] = min(A[i][j-1], A[i+1][j]) +1。
最后返回A[0][n-1]就行了。
- int makepalindrome(string s){
- if(s.empty()) return 0;
- int n = s.length();
- //define A[i][j] as the min number needed to make palindrome from pos i to pos j.
- vector<vector<int> > A(n,vector<int>(n,n));
- //initialize substr with 1 and 2 chars.
- for(int i = 0; i < n; i++){
- A[i][i] = 0;
- if(i < n-1) {
- if(s[i] == s[i+1]) A[i][i+1] = 0;
- else A[i][i+1] = 1;
- }
- }
- //calculate substr from i to j with more than 2 chars.
- for(int j = 2; j < n; j++){
- for(int i = j-2; i >= 0; i--){
- if(s[i] == s[j]) A[i][j] = A[i+1][j-1];
- else A[i][j] = min(A[i][j-1], A[i+1][j]) + 1;
- }
- }
- return A[0][n-1];
- }
No comments:
Post a Comment