- /**
- * filename: LevenshteinEDRule.java
- * package:
- * author: Nick Ma
- * email: nick.ma85@yahoo.com
- * date: 2008-11-28
- * description: this class implements Levenshtein Distance Algorithm to get edit distance
- */
- public class LevenshteinEDRule implements EditDistanceRule {
- /* (non-Javadoc)
- * @see spellChecker.EditDistanceRule#getDistance(java.lang.String, java.lang.String)
- */
- @Override
- public int getDistance(String s, String t) {
- // TODO Auto-generated method stub
- char[] sChars = s.toCharArray();
- char[] tChars = t.toCharArray();
- int[][] matrix = new int[sChars.length+1][tChars.length+1];
- for(int i = 0; i < sChars.length+1; i++) {
- matrix[i][0] = i;
- }
- for(int i = 0; i < tChars.length+1; i++) {
- matrix[0][i] = i;
- }
- for(int i = 1; i < sChars.length+1; i++) {
- for(int j = 1; j < tChars.length+1; j++) {
- int cost = 0;
- if(sChars[i-1] == tChars[j-1]) {
- cost = 0;
- } else {
- cost = 1;
- }
- matrix[i][j] = this.min(
- matrix[i-1][j]+1, // deletion
- matrix[i][j-1]+1, // insertion
- matrix[i-1][j-1]+cost); // substitution
- }
- }
- //printMatrix(matrix);
- return matrix[sChars.length][tChars.length];
- }
- /**
- * description: get the minimum integer of three integers
- * @param a - one of the three integers
- * @param b - one of the three integers
- * @param c - one of the three integers
- * @return - the minimum integer
- */
- private int min(int a, int b, int c) {
- int min = a < b ? a : b;
- min = c < min ? c : min;
- return min;
- }
- /**
- * description: print the matrix
- * @param matrix - input data
- */
- private void printMatrix(int[][] matrix) {
- for(int i = 0; i < matrix.length; i++) {
- for(int j = 0; j < matrix[0].length; j++) {
- System.out.print(matrix[i][j] + " ");
- }
- System.out.println();
- }
- }
- }