if (source.charAt(row - 1) != target.charAt(col – 1)) { cost = _costOfSubstitution;
}
return grid[row - 1][col - 1] + cost;
}
The method deleteCost() calculates the cost of deletion by adding the cumulative value from the cell directly above to the unit cost of deletion:
private int deleteCost(int[][] grid, int row, int col) { return grid[row - 1][col] + _costOfDeletion;
}
Lastly, insertCost() calculates the cost of insertion. This time, you add the cumulative value from the cell directly to the left of the unit cost of insertion and return that to the caller:
private int insertCost(int[][] grid, int row, int col) { return grid[row][col - 1] + _costOfInsertion;
}
The method minimumCost calculates the cost of each of the three operations and passes these to min() — a convenience method for finding the minimum of three values:
private int minimumCost(CharSequence source, CharSequence target, int[][] grid, int row, int col) {
return min(
substitutionCost(source, target, grid, row, col), deleteCost(grid, row, col),
insertCost(grid, row, col)
);
}
private static int min(int a, int b, int c) { return Math.min(a, Math.min(b, c));
}
Now we can get into the algorithm proper. For this, you defined the method calculate(), which takes two strings — a source and a target — and returns the edit distance between them.
The method starts off by initializing a grid with enough rows and columns to accommodate the calculation, and the top-left cell of the grid is initialized to 0. Then, each column in the first row and each row in the first column are initialized, with the resulting grid looking something like the one shown in Figure 17-11.
Next, you iterate over each combination of source and target character, calculating the minimum cost and storing it in the appropriate cell. Eventually, you finish processing all character combinations, at which point you can select the value from the cell at the very bottom-right of the grid (as we did in Figure 17-13) and return that to the caller as the minimum distance:
public int calculate(CharSequence source, CharSequence target) { assert source != null : “source can’t be null”;