PageRenderTime 35ms CodeModel.GetById 16ms app.highlight 14ms RepoModel.GetById 2ms app.codeStats 0ms

/src/org/ooc/frontend/Levenshtein.java

http://github.com/nddrylliog/ooc
Java | 98 lines | 53 code | 28 blank | 17 comment | 13 complexity | 37de4e6fd8fdee164fbdb2ae1fa5c161 MD5 | raw file
 1package org.ooc.frontend;
 2
 3/**
 4 * Computes the Levenshtein distance between two strings
 5 * @author Michael Gilleland
 6 */
 7public class Levenshtein {
 8
 9	// ****************************
10	// Get minimum of three values
11	// ****************************
12
13	protected static int min(int a, int b, int c) {
14		int mi;
15
16		mi = a;
17		if (b < mi) {
18			mi = b;
19		}
20		if (c < mi) {
21			mi = c;
22		}
23		return mi;
24
25	}
26
27	// *****************************
28	// Compute Levenshtein distance
29	// *****************************
30
31	public static int distance(String s, String t) {
32		int d[][]; // matrix
33		int n; // length of s
34		int m; // length of t
35		int i; // iterates through s
36		int j; // iterates through t
37		char s_i; // ith character of s
38		char t_j; // jth character of t
39		int cost; // cost
40
41		// Step 1
42
43		n = s.length();
44		m = t.length();
45		if (n == 0) {
46			return m;
47		}
48		if (m == 0) {
49			return n;
50		}
51		d = new int[n + 1][m + 1];
52
53		// Step 2
54
55		for (i = 0; i <= n; i++) {
56			d[i][0] = i;
57		}
58
59		for (j = 0; j <= m; j++) {
60			d[0][j] = j;
61		}
62
63		// Step 3
64
65		for (i = 1; i <= n; i++) {
66
67			s_i = s.charAt(i - 1);
68
69			// Step 4
70
71			for (j = 1; j <= m; j++) {
72
73				t_j = t.charAt(j - 1);
74
75				// Step 5
76
77				if (s_i == t_j) {
78					cost = 0;
79				} else {
80					cost = 1;
81				}
82
83				// Step 6
84				
85				d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1,
86						d[i - 1][j - 1] + cost);
87
88			}
89
90		}
91
92		// Step 7
93		
94		return d[n][m];
95
96	}
97
98}