levenshteinDistance method

int levenshteinDistance(
  1. String other
)

Returns the Levenshtein edit distance between this string and other.

'kitten'.levenshteinDistance('sitting') // 3

Implementation

int levenshteinDistance(String other) {
  if (isEmpty) return other.length;
  if (other.isEmpty) return length;
  final a = this, b = other;
  final rows =
      List.generate(a.length + 1, (i) => List.filled(b.length + 1, 0));
  for (var i = 0; i <= a.length; i++) {
    rows[i][0] = i;
  }
  for (var j = 0; j <= b.length; j++) {
    rows[0][j] = j;
  }
  for (var i = 1; i <= a.length; i++) {
    for (var j = 1; j <= b.length; j++) {
      final cost = a[i - 1] == b[j - 1] ? 0 : 1;
      rows[i][j] = math.min(
        math.min(rows[i - 1][j] + 1, rows[i][j - 1] + 1),
        rows[i - 1][j - 1] + cost,
      );
    }
  }
  return rows[a.length][b.length];
}