@@ -8,9 +8,11 @@ public static void main(String[] args) {
88 String s2 = "acgb" ;
99
1010 System .out .println (editDistance (s1 , s2 )); // 2
11+ System .out .println (editDistanceIterative (s1 , s2 )); // 2
1112 }
1213
1314 // minimum changes required to make s2 equal to s1
15+ // O(2^nm) Time, where n is length of s1, m is length of s2
1416 public static int editDistance (String s1 , String s2 ) {
1517
1618 if (s1 .length () == 0 )
@@ -35,4 +37,37 @@ public static int editDistance(String s1, String s2) {
3537
3638 return result ;
3739 }
40+
41+ // DP approach
42+ // O(nm) Time, where n is length of s1, m is length of s2
43+ public static int editDistanceIterative (String s1 , String s2 ) {
44+ int [][] storage = new int [s1 .length () + 1 ][s2 .length () + 1 ];
45+
46+ // seed value
47+ storage [s1 .length ()][s2 .length ()] = 0 ;
48+
49+ for (int row = s1 .length (); row >= 0 ; row --) {
50+ for (int col = s2 .length (); col >= 0 ; col --) {
51+
52+ if (row == s1 .length ()) {
53+ storage [row ][col ] = s2 .length () - col ;
54+ continue ;
55+ }
56+
57+ if (col == s2 .length ()) {
58+ storage [row ][col ] = s1 .length () - row ;
59+ continue ;
60+ }
61+
62+ if (s1 .charAt (row ) == s2 .charAt (col )) {
63+ storage [row ][col ] = storage [row + 1 ][col + 1 ];
64+ } else {
65+ storage [row ][col ] = 1 + Math .min (storage [row + 1 ][col + 1 ],
66+ Math .min (storage [row + 1 ][col ], storage [row ][col + 1 ]));
67+ }
68+ }
69+ }
70+
71+ return storage [0 ][0 ];
72+ }
3873}
0 commit comments