最少插入的字符个数,使原字符串变成回文串(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 }
 
 

 

 
 

转载于:https://www.cnblogs.com/liuzhiminxd/p/3964844.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值