您的位置:首页 > 其它

动态规划 递归 例子 string 回文串-最长公共子串

2017-04-02 16:41 330 查看
1.递归 时间超时

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: