動態規劃 遞歸 例子 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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章