最少插入的字符个数,使原字符串变成回文串(leetcode)

引用网址:http://www.ituring.com.cn/article/60247

例如:

1. ab最少插入1个字符,变为*b*ab

2. aa最少插入0个字符

3. abcd最少插入3个字符,*dcb*abcd

 

分析:

1. 如果str[0]==str[n-1],则问题转变为求str[1,n-2],插入最少字符,得到回文

2. 如果str[0]!=str[n-1],则需要插入一个字符要么和str[0]相同,要么和str[n-1]相同,

    1. 如果和str[0],则转变为str[1,n-1],插入最少字符,得到回文

    2. 如果和str[n-1],则转变为str[0,n-2],插入最少字符,得到回文

递归表达式:min(str,low,high)=(str[low]==str[high])? min(str,low+1,high-1): (min( min(str,low,high-1),min(str,low+1,high))+1)
1 int palindromeInsert(char* str){
2     int n=strlen(str);
3     int table[n][n];
4     memset(table,0,sizeof(table));
5     for(int gap=1;gap<n;gap++)
6         for(int low=0,high=low+gap;high<n;low++,high++)
7             table[low][high]=(str[low]==str[high])? table[low+1][high-1]: (fmin(table[low+1][high],table[low][high-1])+1);
8     return table[0][n-1];
9 }

 

 
 
posted @ 2014-09-10 17:24  liuzhiminxd  阅读(1953)  评论(0编辑  收藏  举报