-
Notifications
You must be signed in to change notification settings - Fork 6
/
MinimumEditDistance.java
64 lines (53 loc) · 1.82 KB
/
MinimumEditDistance.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Created by achoudhary on 21/12/2015.
*/
import java.util.*;
public class MinimumEditDistance {
/**
*
* @param word1
* @param word2
* @return
*/
public int minSteps(String word1, String word2){
char[] charFirst = word1.toCharArray(); //Ctrl+Alt+V
char[] charSec = word2.toCharArray();
int[][] table = new int[charSec.length+1][charFirst.length+1]; //column representation is first
//creating the first skeleton row and column filling
for(int i=0;i<= charFirst.length;i++){
table[0][i] = i;
}
for(int i=0;i<= charSec.length;i++){
table[i][0] = i;
}
//make sure to update the array with one increment
//if we keep i it actually means previous row as (i+1) is the main
// row to be tracked as we are supposed to ignore first row and first
//column with default value
for(int i=0;i<charSec.length;i++){
for(int j=0;j<charFirst.length;j++){
if(charSec[i] == charFirst[j]){
table[i+1][j+1] = table[i][j];
}else{
table[i+1][j+1] = Math.min(Math.min(table[i][j],table[i][j+1]),table[i+1][j])+1;
}
}
}
printGrid(table);
return table[table.length-1][table[0].length-1];
}
public static void main(String[] args){
System.out.println("Minimum Step Required to Convert a String to another :=> "+new MinimumEditDistance().minSteps("abcdef","azced")) ;
}
public void printGrid(int[][] input)
{
for(int i = 0; i < input.length; i++)
{
for(int j = 0; j < input[0].length; j++)
{
System.out.printf("%5d ", input[i][j]);
}
System.out.println();
}
}
}