AlanGomes

Similaridade

Mar 7th, 2015
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.32 KB | None | 0 0
  1. package com.brinedev.hank;
  2.  
  3. public class StringSimilarity {
  4.  
  5.     public static double similaridade(String s1, String s2) {
  6.         try {
  7.         return similaridade1(s1,s2)*100;
  8.         } catch (Exception e) {return 0;}
  9.     }
  10.    
  11.   private static double similaridade1(String s1, String s2) {
  12.     String longer = s1, shorter = s2;
  13.     if (s1.length() < s2.length()) {
  14.       longer = s2; shorter = s1;
  15.     }
  16.     int longerLength = longer.length();
  17.     if (longerLength == 0) { return 1.0; }
  18.     return (longerLength - editDistance(longer, shorter)) / (double) longerLength;
  19.  
  20.   }
  21.  
  22.   private static int editDistance(String s1, String s2) {
  23.     s1 = s1.toLowerCase();
  24.     s2 = s2.toLowerCase();
  25.  
  26.     int[] costs = new int[s2.length() + 1];
  27.     for (int i = 0; i <= s1.length(); i++) {
  28.       int lastValue = i;
  29.       for (int j = 0; j <= s2.length(); j++) {
  30.         if (i == 0)
  31.           costs[j] = j;
  32.         else {
  33.           if (j > 0) {
  34.             int newValue = costs[j - 1];
  35.             if (s1.charAt(i - 1) != s2.charAt(j - 1))
  36.               newValue = Math.min(Math.min(newValue, lastValue),
  37.                   costs[j]) + 1;
  38.             costs[j - 1] = lastValue;
  39.             lastValue = newValue;
  40.           }
  41.         }
  42.       }
  43.       if (i > 0)
  44.         costs[s2.length()] = lastValue;
  45.     }
  46.     return costs[s2.length()];
  47.   }
  48.  
  49. }
Advertisement
Add Comment
Please, Sign In to add comment