Skip to content

Commit 9eee1a0

Browse files
Junxu LuMeteorix
Junxu Lu
authored andcommitted
FEA add levenshtein_distance (#2)
* FEA add levenshtein_distance * MOD .gitignore * FIX bug
1 parent ba80e3a commit 9eee1a0

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -9,3 +9,4 @@ build
99
dist
1010
tmp
1111
.vscode
12+
.idea/

src/main.cpp

+38
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,36 @@ vector<int> lcs2_of_list(const string &str1, vector<string> &str_list){
130130
}
131131

132132

133+
// 编辑距离
134+
int levenshtein_distance(const string &str1, const string &str2) {
135+
if (str1 == "" || str2 == "")
136+
return 0;
137+
vector<string> s1 = utf8_split(str1);
138+
vector<string> s2 = utf8_split(str2);
139+
int m = s1.size();
140+
int n = s2.size();
141+
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
142+
int i, j;
143+
144+
for (i = 0; i <= m; i++) {
145+
dp[i][0] = i;
146+
}
147+
for (j = 0; j <= n; j++) {
148+
dp[0][j] = j;
149+
}
150+
for (i = 1; i <= m; i++) {
151+
for (j = 1; j <= n; j++) {
152+
if (s1[i - 1] == s2[j - 1]) {
153+
dp[i][j] = dp[i - 1][j - 1];
154+
} else {
155+
dp[i][j] = 1 + min({dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]});
156+
}
157+
}
158+
}
159+
return dp[m][n];
160+
}
161+
162+
133163
namespace py = pybind11;
134164

135165

@@ -150,4 +180,12 @@ PYBIND11_MODULE(pylcs, m) {
150180
Longest common substring of list
151181
)pbdoc");
152182

183+
m.def("levenshtein_distance", &levenshtein_distance, R"pbdoc(
184+
Levenshtein Distance of Two Strings
185+
)pbdoc");
186+
187+
m.def("edit_distance", &levenshtein_distance, R"pbdoc(
188+
Same As levenshtein_distance(): Levenshtein Distance of Two Strings
189+
)pbdoc");
190+
153191
}

0 commit comments

Comments
 (0)