这是我放在一起的东西,本质上是通过基于连续字符数的查询突出显示最接近的匹配项
公共类 SequenceMatches {
public static void main(String [] args)
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
String query = "P's SalmonCat ";
map = addTermsToHashMap(map);// add terms to a hash map
map = compareFirstCharacter(map, query);// compare the initial first character
map= compareSequentialCharacters(map, query);// compare terms to query and add score based on the number of matches
printResults(map);
}
public static HashMap<String,Integer> addTermsToHashMap(HashMap<String,Integer> map){
String term = "Popeye's CatFish";
String otherTerm = "Popets CatSalmon";
map.put(term,0);
map.put(otherTerm,0);
return map;
}
public static HashMap<String,Integer> compareFirstCharacter(HashMap<String,Integer> map,String query){
for(Map.Entry<String,Integer> e: map.entrySet())
{
String term = e.getKey();
char [] termChar = term.toCharArray();
char [] queryChar = query.toCharArray();
if((queryChar[0]) == (termChar[0]))
{
int value = map.get(term);
map.put(term,++value);
}
}
return map;
}
public static HashMap<String,Integer> compareSequentialCharacters(HashMap<String,Integer> map,String query){
for(Map.Entry<String,Integer> e: map.entrySet())
{
String term = e.getKey();
char [] termChar = term.toCharArray();
char [] queryChar = query.toCharArray();
for(int i = 0; i < queryChar.length -1; i++)
{
for(int j = 0; j < termChar.length -1; j++)
{
if(queryChar[i] == termChar[j] )
{
if((queryChar[i + 1]) == (termChar[j + 1]))
{
System.out.println((queryChar[i + 1]) + " " + (termChar[j + 1]));
int value = map.get(term);
map.put(term,++value);
break;
}
}
}
}
}
return map;
}
public static void printResults(HashMap<String,Integer> map)
{
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey()+" : "+entry.getValue());
}
}
}