

注解
1、本题理解题意是关键。题目意思是给两个字符串,位置可以任意匹配(翻译一下就是:最极端的两种情况,第一种是第二个字符串的最后一个字符去匹配第一个字符串的第一个字符,第二种是第二个字符串的第一个字符去匹配第一个字符串的最后一个字符)。求其中匹配数目最多的一种情况。然后乘2作为分子。分母是两个字符串的长度之和。
2、求GCD最大公约数,化简分数。
3、字符串匹配的方法:为了简单,可以把第一个字符串加长,加长的方式是首尾加上一定数目的括号。括号的数目其实就是第二个字符串长度减一。
代码
#include <iostream>
using namespace std;
string s1, tmps1;
string s2;
int nume, deno;
int gcd(int a, int b) {
return a%b==0?b:gcd(b, a%b);
}
void prework() {
for(int i=0; i<s2.length()-1; i++) {
tmps1 = " " + tmps1;
}
for(int i=0; i<s2.length()-1; i++) {
tmps1 = tmps1 + " ";
}
}
void mainwork() {
int maxn = 0;
for(int i=0; i<tmps1.length(); i++) {
int common = 0;
for(int j=0; j<s2.length(); j++) {
if(i+j<tmps1.length() && tmps1.at(i+j)==s2.at(j)) {
common++;
}
}
if(common>maxn) {
maxn = common;
}
}
nume = maxn*2;
deno = s1.length()+s2.length();
int g = gcd(nume, deno);
nume /= g;
deno /= g;
}
void print() {
if(deno!=1) {
cout<<"appx("<<s1<<","<<s2<<") = "<<nume<<"/"<<deno<<endl;
} else {
cout<<"appx("<<s1<<","<<s2<<") = "<<nume<<endl;
}
}
int main() {
cin>>s1;
while(s1.compare("-1")) {
tmps1 = s1;
cin>>s2;
prework();
mainwork();
print();
cin>>s1;
}
return 0;
}
结果

本文介绍了一种解决字符串匹配问题的算法,通过扩展第一个字符串并遍历匹配第二个字符串的所有可能位置,找到最大匹配数。随后,算法计算匹配比率,并通过求最大公约数(GCD)来化简该比率。
642

被折叠的 条评论
为什么被折叠?



