1092 回文字符串
来源:互联网 发布:杭州淘宝拍摄公司 编辑:程序博客网 时间:2024/06/14 17:21
点击打开链接
回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。每个字符串都可以通过向中间添加一些字符,使之变为回文字符串。
例如:abbc 添加2个字符可以变为 acbbca,也可以添加3个变为 abbcbba。方案1只需要添加2个字符,是所有方案中添加字符数量最少的。
Input
输入一个字符串Str,Str的长度 <= 1000。
Output
输出最少添加多少个字符可以使之变为回文字串。
Input示例
abbc
Output示例
2
解法一:
因为是只能添加字符,所以把原字符串a转置为b,然后求a,b的最长公共子序列,然后总长度减去最长公共子序列长度即为所求。
#include<bits/stdc++.h>#define ll long longusing namespace std;const int maxn=1010;string a,b;int dp[maxn][maxn];int main(){ cin>>b; a=b; reverse(b.begin(),b.end()); for(int i=1;i<=a.size();++i){ for(int j=1;j<=b.size();++j){ if(a[i-1]==b[j-1]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } cout<<a.size()-dp[a.size()][b.size()]<<endl; return 0;}
解法二:
区间dp ,
如果首尾相同,那么dp[l][r]=dp[l+!][r-1],否则 dp[l][r]=min(dp[l+1][r],dp[l][r-1]);
#include<bits/stdc++.h>#define ll long longusing namespace std;const int maxn=1010;string a;int dp[maxn][maxn];int main(){ cin>>a; for(int i=1;i<=a.size();++i){ for(int j=0;j<a.size()-i;++j){ int l=j,r=j+i; if(a[l]==a[r]) dp[l][r]=dp[l+1][r-1]; else dp[l][r]=min(dp[l+1][r],dp[l][r-1])+1; } } cout<<dp[0][a.size()-1]<<endl; return 0;}
阅读全文
0 0
- 1092 回文字符串
- 1092 回文字符串
- 【51nod】1092 回文字符串
- 1092 回文字符串(51nod)
- 51 nod 1092 回文字符串
- 51nod 1092 回文字符串
- 51nod 1092 回文字符串
- 51nod-【1092 回文字符串】
- 51nod 1092 回文字符串
- 51Nod 1092 回文字符串
- 51nod 1092 回文字符串
- 51Nod 1092 回文字符串
- 51nod 1092 回文字符串
- 51nod 1092 回文字符串
- 还是回文 && 回文字符串
- 字符串回文
- 回文字符串
- 回文字符串
- 【MQTT】在Windows下搭建MQTT服务器
- MATLAB中写TXT文件换行的实现
- 轻松打造APP统一标题栏
- 设置ls -l命令中显示的日期格式
- python 入门一(数据结构)
- 1092 回文字符串
- js实现ajax
- 继YouCompleteMe后,这又是一个vim用户change life的插件
- RN开源播放器Video组件(react-native-video)
- 关于C语言字符数组、字符串和指针的相关问题
- [RN爬坑日记] run-ios注意事项
- NOIP2017模拟赛(10) 总结
- 使用神经网络对黄金期货交割价格进行预测-2 MATLAB
- [积累] 在Ubuntu16.04 64位系统上配置linux-0.11内核实验环境