AlanGomes

Untitled

Feb 28th, 2015
291
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.82 KB | None | 0 0
  1. package com.brinedev.fixer;
  2.  
  3. public class StringSimilarity {
  4.  
  5.     public static double similaridade(String s1, String s2) {
  6.         try {
  7.         return similarity(s1,s2)*100;
  8.         } catch (Exception e) {return 0;}
  9.     }
  10.    
  11.   /**
  12.    * Calculates the similarity (a number within 0 and 1) between two strings.
  13.    */
  14.   public static double similarity(String s1, String s2) {
  15.     String longer = s1, shorter = s2;
  16.     if (s1.length() < s2.length()) { // longer should always have greater length
  17.       longer = s2; shorter = s1;
  18.     }
  19.     int longerLength = longer.length();
  20.     if (longerLength == 0) { return 1.0; /* both strings are zero length */ }
  21.     /* // If you have StringUtils, you can use it to calculate the edit distance:
  22.     return (longerLength - StringUtils.getLevenshteinDistance(longer, shorter)) /
  23.                                (double) longerLength; */
  24.     return (longerLength - editDistance(longer, shorter)) / (double) longerLength;
  25.  
  26.   }
  27.  
  28.   // Example implementation of the Levenshtein Edit Distance
  29.   // See http://rosettacode.org/wiki/Levenshtein_distance#Java
  30.   public static int editDistance(String s1, String s2) {
  31.     s1 = s1.toLowerCase();
  32.     s2 = s2.toLowerCase();
  33.  
  34.     int[] costs = new int[s2.length() + 1];
  35.     for (int i = 0; i <= s1.length(); i++) {
  36.       int lastValue = i;
  37.       for (int j = 0; j <= s2.length(); j++) {
  38.         if (i == 0)
  39.           costs[j] = j;
  40.         else {
  41.           if (j > 0) {
  42.             int newValue = costs[j - 1];
  43.             if (s1.charAt(i - 1) != s2.charAt(j - 1))
  44.               newValue = Math.min(Math.min(newValue, lastValue),
  45.                   costs[j]) + 1;
  46.             costs[j - 1] = lastValue;
  47.             lastValue = newValue;
  48.           }
  49.         }
  50.       }
  51.       if (i > 0)
  52.         costs[s2.length()] = lastValue;
  53.     }
  54.     return costs[s2.length()];
  55.   }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment