File tree Expand file tree Collapse file tree 2 files changed +86
-0
lines changed Expand file tree Collapse file tree 2 files changed +86
-0
lines changed Original file line number Diff line number Diff line change
1
+ package EditDistance ;
2
+
3
+ /**
4
+ * User: Danyang
5
+ * Date: 1/26/2015
6
+ * Time: 11:09
7
+ *
8
+ * Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation
9
+ * is counted as 1 step.)
10
+
11
+ You have the following 3 operations permitted on a word:
12
+
13
+ a) Insert a character
14
+ b) Delete a character
15
+ c) Replace a character
16
+ */
17
+ public class Solution {
18
+ /**
19
+ * from word1 to word2
20
+ * f[i, j] the min distance from word1[0..i] tp word2[0..j]
21
+ * if word1[i]==word2[j]:
22
+ * f[i][j] = f[i-1][j-1]
23
+ *
24
+ * else:
25
+ * delete: f[i, j] = f[i-1, j]+1
26
+ * insert: f[i, j] = f[i, j-1]+1
27
+ * replace f[i, j] = f[i-1, j-1]+1
28
+ *
29
+ * Notice:
30
+ * 1. the INITIAL condition
31
+ *
32
+ * @param word1
33
+ * @param word2
34
+ * @return
35
+ */
36
+ public int minDistance (String word1 , String word2 ) {
37
+ int m = word1 .length ();
38
+ int n = word2 .length ();
39
+ int [][] f = new int [m +1 ][n +1 ];
40
+ for (int j =0 ; j <n +1 ; j ++)
41
+ f [0 ][j ] = j ;
42
+ for (int i =0 ; i <m +1 ; i ++)
43
+ f [i ][0 ] = i ;
44
+
45
+ for (int i =1 ; i <m +1 ; i ++)
46
+ for (int j =1 ; j <n +1 ; j ++) {
47
+ if (word1 .charAt (i -1 )==word2 .charAt (j -1 ))
48
+ f [i ][j ] = f [i -1 ][j -1 ];
49
+ else {
50
+ f [i ][j ] = Math .min (f [i -1 ][j ]+1 , Math .min (f [i ][j -1 ]+1 , f [i -1 ][j -1 ]+1 ));
51
+ }
52
+ }
53
+ return f [m ][n ];
54
+ }
55
+ }
Original file line number Diff line number Diff line change
1
+ package RemoveElement ;
2
+
3
+ /**
4
+ * User: Danyang
5
+ * Date: 1/26/2015
6
+ * Time: 10:58
7
+ *
8
+ * Given an array and a value, remove all instances of that value in place and return the new length.
9
+
10
+ The order of elements can be changed. It doesn't matter what you leave beyond the new length.
11
+ */
12
+ public class Solution {
13
+ /**
14
+ * Put it to back
15
+ * @param A
16
+ * @param elem
17
+ * @return
18
+ */
19
+ public int removeElement (int [] A , int elem ) {
20
+ int e = A .length -1 ;
21
+ for (int i =0 ; i <=e ; ) {
22
+ if (A [i ]!=elem )
23
+ i ++;
24
+ else {
25
+ int t = A [i ]; A [i ] = A [e ]; A [e ] = t ;
26
+ e --;
27
+ }
28
+ }
29
+ return e +1 ;
30
+ }
31
+ }
You can’t perform that action at this time.
0 commit comments