Here you can find the source of levenshteinDistance(CharSequence s, CharSequence t)
Parameter | Description |
---|---|
s | the first String, must not be null |
t | the second String, must not be null |
public static int levenshteinDistance(CharSequence s, CharSequence t)
//package com.java2s; //License from project: Open Source License public class Main { /**/*from ww w .j a va 2 s . co m*/ * Find the Levenshtein distance between two Strings. * * This is the number of changes needed to change one String into another, * where each change is a single character modification (deletion, insertion or substitution). * * @param s * the first String, must not be null * @param t * the second String, must not be null * @return result distance */ public static int levenshteinDistance(CharSequence s, CharSequence t) { if (s == null || t == null) throw new IllegalArgumentException("Strings must not be null"); int n = s.length(); int m = t.length(); if (n == 0) return m; else if (m == 0) return n; if (n > m) { final CharSequence tmp = s; s = t; t = tmp; n = m; m = t.length(); } int p[] = new int[n + 1]; int d[] = new int[n + 1]; int _d[]; int i; int j; char t_j; int cost; for (i = 0; i <= n; i++) p[i] = i; for (j = 1; j <= m; j++) { t_j = t.charAt(j - 1); d[0] = j; for (i = 1; i <= n; i++) { cost = s.charAt(i - 1) == t_j ? 0 : 1; d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); } _d = p; p = d; d = _d; } return p[n]; } }