forked from rost0413/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEdit_Distance.cpp
More file actions
95 lines (83 loc) · 2.77 KB
/
Edit_Distance.cpp
File metadata and controls
95 lines (83 loc) · 2.77 KB
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
Author: Weixian Zhou, ideazwx@gmail.com
Date: June 28, 2012
Problem: Edit Distance
Difficulty: medium
Source: http://www.leetcode.com/onlinejudge
Notes:
Given two words word1 and word2, find the minimum number of steps required to convert
word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
Solution:
This is a dynamic programming problem. The problem is similar to longest common
substring problem. Here we define f[n, m] as the minimum edit distance of string
a[0..n] and b[0..m]. Then
f[n, m] = f[n-1,m-1], if a[n] == b[m]
= min{f[n-1,m]+1, f[n,m-1]+1, f[n-1,m-1]+1}, if a[n] != b[m].
*/
#include <vector>
#include <set>
#include <climits>
#include <algorithm>
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstring>
using namespace std;
class Solution {
public:
int minimal(int a, int b, int c) {
int min = a;
if (b < min) min = b;
if (c < min) min = c;
return min;
}
int minDistance(string word1, string word2) {
int ed[word1.length() + 1][word2.length() + 1];
// initialize
for (int i = 0; i < word1.length() + 1; i++) {
ed[i][0] = i;
}
for (int i = 0; i < word2.length() + 1; i++) {
ed[0][i] = i;
}
// DP
for (int i = 1; i < word1.length() + 1; i++) {
for (int j = 1; j < word2.length() + 1; j++) {
if (word1[i - 1] == word2[j - 1]) {
ed[i][j] = ed[i -1][j - 1];
}
else {
ed[i][j] = minimal(ed[i - 1][j] + 1,
ed[i][j - 1] + 1,
ed[i - 1][j - 1] + 1);
}
}
}
return ed[word1.length()][word2.length()];
}
};
// java solution by ke (mrhuke@gmail.com)
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int> > distance(word1.size()+1, vector<int>(word2.size()+1, 0));
distance[0][0] = 0;
for ( int i = 1; i <= word1.size(); ++i)
distance[i][0] = i;
for ( int i = 1; i <= word2.size(); ++i)
distance[0][i] = i;
for ( int i = 1; i <= word1.size(); ++i){
for ( int j = 1; j <= word2.size(); ++j){
if (word1[i-1] == word2[j-1])
distance[i][j] = distance[i-1][j-1];
else
distance[i][j] = min(min(distance[i-1][j], distance[i][j-1]), distance[i-1][j-1]) + 1;
}
}
return distance[word1.size()][word2.size()];
}
};