【字符串】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;
}
思路:一开始想多了……拿着就开敲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 1580 String Matching(比较字符串的相似程度,四个for循环即可)
- POJ 1580 String Matching(我的水题之路——字符串公共子串的比较雏形)
- poj 1580 String Matching 【字符串处理】
- POJ 3652 Persistent Bits 简单字符串模拟
- POJ 1731 Orders 按序输出一个字符串的全排列 next_permutation()
- POJ 1051 P,MTHBGWB 简单字符串转换
- POJ 1936 All in all 简单字符串比较
- POJ 2503 字符串查找 qsort+二分查找
- POJ 2406 连续重复字符串(KMP)和后缀数组
- poj 2774 Long Long Message 求两个字符串的最长公共子串 后缀数组
- POJ 3095 Linear Pachinko 字符串模拟
- POJ 2743 字符串判等 解题报告
- POJ 1016(自总结数 字符串处理) 解题报告
- poj 1226 Substrings 求n个字符串的最长公共子串(这里可以是反序相同) 后缀数组
- poj 3294 Life Forms 求n(n>1)个字符串的最长的一个子串 后缀数组
- POJ 3652 Persistent Bits 简单字符串模拟
- 动态规划 加最少字符使字符串变回文 POJ 1159 short水过!
- POJ 2503 字符串查找 qsort+二分查找
- POJ 3157 Java vs C++ 字符串处理
- poj 2337 Catenyms 判断并输出欧拉路 判断N个字符串是否能够首尾相连全部输出(欧拉路)