Java String Distance editDistance(String string1, String string2)

Here you can find the source of editDistance(String string1, String string2)

Description

edit Distance

License

Open Source License

Declaration

public static int editDistance(String string1, String string2) 

Method Source Code

//package com.java2s;

public class Main {
    public static int editDistance(String string1, String string2) {
        int rowCount = string1.length() + 1;
        int columnCount = string2.length() + 1;

        int[][] matrix = new int[rowCount][columnCount];

        for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
            matrix[rowIndex][0] = rowIndex;
        }// www  .j ava  2 s.  c  om

        for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
            matrix[0][columnIndex] = columnIndex;
        }

        for (int rowIndex = 1; rowIndex < matrix.length; rowIndex++) {
            for (int columnIndex = 1; columnIndex < matrix[0].length; columnIndex++) {
                char char1 = string1.charAt(rowIndex - 1);
                char char2 = string2.charAt(columnIndex - 1);
                if (char1 == char2) {
                    matrix[rowIndex][columnIndex] = matrix[rowIndex - 1][columnIndex - 1];
                } else {
                    int left = matrix[rowIndex][columnIndex - 1];
                    int up = matrix[rowIndex - 1][columnIndex];
                    int leftUp = matrix[rowIndex - 1][columnIndex - 1];
                    int distance = Math.min(left, up);
                    distance = Math.min(distance, leftUp);
                    matrix[rowIndex][columnIndex] = distance + 1;
                }
            }
        }

        return matrix[rowCount - 1][columnCount - 1];
    }
}

Related

  1. editDistance(String s, String t)
  2. editDistance(String s, String t)
  3. editDistance(String s0, String s1)
  4. EditDistance(String s1, String s2)
  5. editDistance(String str1, String str2)
  6. editDistance(String word1, String word2)
  7. Sqr(String[] X)