【字符串】poj1582 String Matching

題目大意:給定兩個字符串,求在所有的匹配中,公共字符最多的。


思路:一開始想多了……拿着就開敲dp,求編輯距離……

寫完了才發現不對,推倒重寫,直接暴力出結果

兩重循環枚舉起始點,然後掃一次就行了

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

string s1,s2;

int gcd(int a,int b){
    int c;
    if (a==0) return 1;
    if (a<0) return gcd(-a,b);

    if (a<b){
        int x=a;
        a=b;
        b=x;
    }

    c=b;
    while (b!=0){
        c=a%b;
        a=b;
        b=c;
    }
    return a;

}

int main(){
    while (cin>>s1,s1!="-1"){
        cin>>s2;
        int len1=s1.length(),len2=s2.length();

        cout<<"appx("<<s1<<","<<s2<<") = ";

        int max=0;
        for (int i=0;i<len1;i++)
            for (int j=0;j<len2;j++){
                int p1=i,p2=j;
                int cnt=0;
                while (p1<len1 && p2<len2){
                    if (s1[p1]==s2[p2]) cnt++;
                    p1++;p2++;
                }

                if (cnt*2>max) max=cnt*2;
            }

        if (max==0){
            cout<<0<<endl;
        }
        else if (max==len1+len2){
            cout<<1<<endl;
        }
        else {
            int x=gcd(max,len1+len2);
            cout<<max/x<<"/"<<(len1+len2)/x<<endl;
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章