File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func minDistance( _ word1: String , _ word2: String ) -> Int {
3
+ // No operations needed if strings match
4
+ if word1 == word2 {
5
+ return 0
6
+ }
7
+
8
+ let m = word1. count, n = word2. count
9
+
10
+ // if one word has no characters, min operations is length of other word
11
+ if m == 0 {
12
+ return n
13
+ }
14
+ if n == 0 {
15
+ return m
16
+ }
17
+
18
+ var prev = 0
19
+ var curr = Array ( repeating: 0 , count: n + 1 )
20
+
21
+ // convert the strings into an array
22
+ let newWord1 = Array ( word1)
23
+ let newWord2 = Array ( word2)
24
+
25
+ for j in 1 ... n {
26
+ curr [ j] = j
27
+ }
28
+
29
+ for i in 1 ... m {
30
+ var prev = curr [ 0 ]
31
+ curr [ 0 ] = i
32
+ for j in 1 ... n {
33
+ let temp = curr [ j]
34
+ if newWord1 [ i - 1 ] == newWord2 [ j - 1 ] {
35
+ curr [ j] = prev
36
+ }
37
+ else {
38
+ curr [ j] = min ( prev, min ( curr [ j - 1 ] , curr [ j] ) ) + 1
39
+ }
40
+ prev = temp
41
+ }
42
+ }
43
+ return curr [ n]
44
+ }
45
+ }
You can’t perform that action at this time.
0 commit comments