File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
Interview Prep/section19_DynamicProgramming Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 1+ package section19_DynamicProgramming ;
2+
3+ public class EditDistance {
4+
5+ public static void main (String [] args ) {
6+
7+ String s1 = "agbg" ;
8+ String s2 = "acgb" ;
9+
10+ System .out .println (editDistance (s1 , s2 )); // 2
11+ }
12+
13+ // minimum changes required to make s2 equal to s1
14+ public static int editDistance (String s1 , String s2 ) {
15+
16+ if (s1 .length () == 0 )
17+ return s2 .length ();
18+
19+ if (s2 .length () == 0 )
20+ return s1 .length ();
21+
22+ String ros1 = s1 .substring (1 );
23+ String ros2 = s2 .substring (1 );
24+ int result = 0 ;
25+
26+ if (s1 .charAt (0 ) == s2 .charAt (0 )) {
27+ result = editDistance (ros1 , ros2 );
28+ } else {
29+ int removeFactor = 1 + editDistance (ros1 , ros2 );
30+ int addFactor = 1 + editDistance (ros1 , s2 );
31+ int replaceFactor = 1 + editDistance (s1 , ros2 );
32+
33+ result = Math .min (removeFactor , Math .min (addFactor , replaceFactor ));
34+ }
35+
36+ return result ;
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments