动态规划 递归 例子 string 回文串-最长公共子串
2017-04-02 16:41
330 查看
1.递归 时间超时
2.自顶向下的 动态规划
3.加入 stl vector
2.自顶向下的 动态规划
3.加入 stl vector
#include <iostream> #include <string> #include <algorithm> using namespace std; int LCS( string str1,string str2) { string a=str1.substr(0, str1.size() - 1); string b=str2.substr(0, str2.size() - 1); string c=str1.substr(0, str1.size() ); string d=str2.substr(0, str2.size() ); if (str1 == "" || str2 == "") return 0; else if (str1.back() == str2.back()) return LCS(a, b) + 1; else return max(LCS(a,d), LCS(c, b)); } int main() { string str1; while (getline(cin,str1)) { string str2(str1); reverse(str1.begin(), str1.end()); cout<<str1.length()-LCS(str1, str2); } return 0; }
#include<iostream> #include<string> #include<algorithm> using namespace std; const int MAX = 1001; int MaxLen[MAX][MAX]; //最长公共子序列,动态规划求法 int maxLen(string s1, string s2){ int length1 = s1.size(); int length2 = s2.size(); for (int i = 0; i < length1; ++i) MaxLen[i][0] = 0; for (int i = 0; i < length2; ++i) MaxLen[0][i] = 0; for (int i = 1; i <= length1; ++i) { for (int j = 1; j <= length2; ++j) { if (s1[i-1] == s2[j-1]){ MaxLen[i][j] = MaxLen[i-1][j - 1] + 1; } else { MaxLen[i][j] = max(MaxLen[i - 1][j], MaxLen[i][j - 1]); } } } return MaxLen[length1][length2]; } int main(){ string s; while (cin >> s){ int length = s.size(); if (length == 1){ cout << 1 << endl; continue; } //利用回文串的特点 string s2 = s; reverse(s2.begin(),s2.end()); int max_length = maxLen(s, s2); cout << length - max_length << endl; } return 0; }
#include <stdio.h> #include <iostream> #include <string.h> #include <vector> #include <string> using namespace std; int main(){ string s; while(cin>>s){ int len = s.length(); int maxlen = 0; vector<vector<int> > Vec; for(int i = 0 ; i < len+1 ; i++){ vector<int> temp(len+1,0); Vec.push_back(temp); } for(int i = 1; i< len+1 ; i++){ for(int j = 1 ; j < len+1;j++){ if(s[i-1]==s[len-j]){ Vec[i][j] = Vec[i-1][j-1]+1; } else { Vec[i][j] = max(Vec[i-1][j],Vec[i][j-1]); } } } cout<<len-Vec[len][len]<<endl; } }
相关文章推荐
- 动态规划之最长公共子串(递归的备忘录写法)
- acm动态规划之LCS最长公共子串uva10405Longest Common Subsequence解题报告
- 动态规划2 - 最长公共子序列与最长公共子串
- 动态规划:最长公共子串长度
- 动态规划之最长公共子序列&最长公共子串
- 动态规划-最长公共子串问题的实现
- 动态规划求最长公共子串
- 动态规划-最长公共子序列、最长公共子串
- 动态规划:最长公共子序列与最长公共子串
- 动态规划:求最长公共子串/最长公共子序列
- 动态规划之最长公共子串
- 动态规划 - 最长公共子序列 - 最长公共子串 - 最长不重复子串 - 最长递增子序列 - 最长回文子串
- 动态规划 最长公共子序列LCS、最长公共连续子串、最长重复子串
- 动态规划:求最长公共子串/最长公共子序列
- 最长公共子串LCS--之动态规划
- acm动态规划之LCS最长公共子串uva10405Longest Common Subsequence解题报告
- 动态规划方法求解最长公共子串
- 动态规划解决最长公共子序列和最长公共子串
- 最长公共子串(动态规划的思想)
- 转【算法之动态规划(三)】动态规划算法之:最长公共子序列 & 最长公共子串(LCS)&字符串相似度算法