001package es.ucm.fdi.gaia.jcolibri.method.retrieve.NNretrieval.similarity.local; 002 003 004import es.ucm.fdi.gaia.jcolibri.exception.NoApplicableSimilarityFunctionException; 005import es.ucm.fdi.gaia.jcolibri.method.retrieve.NNretrieval.similarity.LocalSimilarityFunction; 006 007/** 008 * This function returns a similarity value depending of the biggest substring 009 * that belong to both strings. 010 */ 011public class MaxString implements LocalSimilarityFunction { 012 013 014 /** 015 * Applies the similarity function. 016 * 017 * @param s 018 * String. 019 * @param t 020 * String. 021 * @return result of apply the similarity funciton. 022 */ 023 public double compute(Object s, Object t) throws NoApplicableSimilarityFunctionException 024{ 025 if ((s == null) || (t == null)) 026 return 0; 027 if (!(s instanceof String)) 028 throw new NoApplicableSimilarityFunctionException(this.getClass(), s.getClass()); 029 if (!(t instanceof String)) 030 throw new NoApplicableSimilarityFunctionException(this.getClass(), s.getClass()); 031 032 033 String news = (String) s; 034 String newt = (String) t; 035 if (news.equals(newt)) 036 return 1.0; 037 else 038 return ((double) MaxSubString(news, newt) / (double) Math.max(news 039 .length(), newt.length())); 040 } 041 042 /** 043 * Returns the length of the biggest substring that belong to both strings. 044 * 045 * @param s 046 * @param t 047 * @return 048 */ 049 private int MaxSubString(String s, String t) { 050 String shorter = (s.length() > t.length()) ? t : s; 051 String longer = (shorter.equals(s)) ? t : s; 052 int best = 0; 053 for (int i = 0; i < shorter.length(); i++) { 054 for (int j = shorter.length(); j > i; j--) { 055 if (longer.indexOf(shorter.substring(i, j)) != -1) 056 best = Math.max(best, j - i); 057 } 058 } 059 return best; 060 } 061 062 /** Applicable to String */ 063 public boolean isApplicable(Object o1, Object o2) 064 { 065 if((o1==null)&&(o2==null)) 066 return true; 067 else if(o1==null) 068 return o2 instanceof String; 069 else if(o2==null) 070 return o1 instanceof String; 071 else 072 return (o1 instanceof String)&&(o2 instanceof String); 073 } 074}