Wednesday, May 15, 2013

Convert string to palindrome C++

Find minimum number of characters that need to be inserted into a string (anywhere in the string) to make it a palindrome
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]就行了。

  1. int makepalindrome(string s){  
  2.    if(s.empty()) return 0;  
  3.    int n = s.length();  
  4.   
  5.    //define A[i][j] as the min number needed to make palindrome from pos i to pos j.  
  6.    vector<vector<int> > A(n,vector<int>(n,n));  
  7.   
  8.    //initialize substr with 1 and 2 chars.  
  9.    for(int i = 0; i < n; i++){  
  10.   
  11.      A[i][i] = 0;  
  12.   
  13.      if(i < n-1) {  
  14.   
  15.         if(s[i] == s[i+1]) A[i][i+1] = 0;  
  16.   
  17.         else A[i][i+1] =  1;  
  18.      }    
  19.    }  
  20.   
  21.    //calculate substr from i to j with more than 2 chars.  
  22.    for(int j = 2; j < n; j++){  
  23.   
  24.       for(int i = j-2; i >= 0; i--){  
  25.   
  26.          if(s[i] == s[j]) A[i][j] = A[i+1][j-1];  
  27.   
  28.          else A[i][j] = min(A[i][j-1], A[i+1][j]) + 1;  
  29.      }  
  30.   }  
  31.   
  32.   return A[0][n-1];  
  33. }     

No comments:

Post a Comment