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

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值