classSolution{ publicintminDistance(String word1, String word2){ char[] a = word1.toCharArray(), b = word2.toCharArray(); int m = a.length, n = b.length; int[][] dis = newint[m + 1][n + 1]; for ( int i = 0; i < m; i++ ) Arrays.fill(dis[i], -1); for ( int i = 0; i <= m; i++ ) dis[i][n] = m - i; for ( int j = 0; j <= n; j++ ) dis[m][j] = n - j; return myDis( a, b, 0, 0, dis ); }
privateintmyDis( char[] a, char[] b, int i, int j, int[][] dis ){ if ( dis[i][j] != -1 ) return dis[i][j]; if ( a[i] == b[j] ) { dis[i][j] = myDis( a, b, i + 1, j + 1, dis ); } else { int dis1 = myDis( a, b, i, j + 1, dis ); int dis2 = myDis( a, b, i + 1, j, dis ); int dis3 = myDis( a, b, i + 1, j + 1, dis ); int min = dis1 < dis2 ? dis1 : dis2; min = min < dis3 ? min : dis3; dis[i][j] = min + 1; } return dis[i][j]; } }