您的位置:首页 > 其它

【字符串】poj1582 String Matching

2014-07-15 13:23 162 查看
题目大意:给定两个字符串,求在所有的匹配中,公共字符最多的。

思路:一开始想多了……拿着就开敲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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj