72. Edit Distance
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
---
public class Solution { public int minDistance(String word1, String word2) { if(word1==null || word2==null) return 0; int n1 = word1.length(); int n2 = word2.length(); if(n1==0) return n2; if(n1==0) return n1; int[][] dist = new int[n1+1][n2+1]; for(int i=0; i<=n1; i++){ dist[i][0] = i; } for(int j=0; j<=n2; j++){ dist[0][j] = j; } for(int i=0; i<n1; i++){ int v1 = word1.charAt(i); for(int j=0; j<n2; j++){ int v2 = word2.charAt(j); if(v1 == v2) dist[i+1][j+1] = dist[i][j]; else{ int min = Math.min(dist[i][j], dist[i][j+1]); dist[i+1][j+1] = Math.min(dist[i+1][j],min) + 1; } } } return dist[n1][n2]; } }
浙公网安备 33010602011771号