2013
11-09

# String Matching

It’s easy to tell if two words are identical – just check the letters. But how do you tell if two words are almost identical? And how close is “almost”?

There are lots of techniques for approximate word matching. One is to determine the best substring match, which is the number of common letters when the words are compared letter-byletter.

The key to this approach is that the words can overlap in any way. For example, consider the words CAPILLARY and MARSUPIAL. One way to compare them is to overlay them:

CAPILLARY

MARSUPIAL

There is only one common letter (A). Better is the following overlay:

CAPILLARY

MARSUPIAL

with two common letters (A and R), but the best is:

CAPILLARY

MARSUPIAL

Which has three common letters (P, I and L).

The approximation measure appx(word1, word2) for two words is given by:

common letters * 2

—————————–

length(word1) + length(word2)

Thus, for this example, appx(CAPILLARY, MARSUPIAL) = 6 / (9 + 9) = 1/3. Obviously, for any word W appx(W, W) = 1, which is a nice property, while words with no common letters have an appx value of 0.

The input for your program will be a series of words, two per line, until the end-of-file flag of -1.

Using the above technique, you are to calculate appx() for the pair of words on the line and print the result.

The words will all be uppercase.

Print the value for appx() for each pair as a reduced fraction,Fractions reducing to zero or one should have no denominator.

CAR CART
TURKEY CHICKEN
MONEY POVERTY
ROUGH PESKY
A A
-1

appx(CAR,CART) = 6/7
appx(TURKEY,CHICKEN) = 4/13
appx(MONEY,POVERTY) = 1/3
appx(ROUGH,PESKY) = 0
appx(A,A) = 1

//* @author: [email protected]
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
while(true)
{
String s1=in.next();
if(s1.equals("-1"))break;
String s2=in.next();
int max=0;
for(int i=0;i< s1.length();i++)
{
int count =0;
for(int j=0;j< s2.length();j++)
{
boolean bb=true;
if(i+j>=s1.length())
{
bb=false;
break;
}
if(!bb)break;
if(s1.charAt(i+j)==s2.charAt(j))count++;
}
if(count>max)max=count;
}
for(int i=0;i< s2.length();i++)
{
int count =0;
for(int j=0;j< s1.length();j++)
{
boolean bb=true;
if(i+j>=s2.length())
{
bb=false;
break;
}
if(!bb)break;
if(s2.charAt(i+j)==s1.charAt(j))count++;
}
if(count>max)max=count;
}
int total=s1.length()+s2.length();
int sum=max*2;
System.out.print("appx("+s1+","+s2+") = ");
if(sum==0)System.out.println(0);
else if(sum==total)System.out.println(1);
else
{
while(true)
{
boolean bb=false;
for(int i=2;i<=sum;i++)
{
if(sum%i==0&&total%i==0)
{
sum/=i;
total/=i;
bb=true;
}
}
if(!bb)break;
}
System.out.println(sum+"/"+total);
}

}
}
}

1. 题目需要求解的是最小值，而且没有考虑可能存在环，比如
0 0 0 0 0
1 1 1 1 0
1 0 0 0 0
1 0 1 0 1
1 0 0 0 0
会陷入死循环