AlgoPlus v0.1.0
Loading...
Searching...
No Matches
edit_distance.h
1#ifndef MIN_DISTANCE_H
2#define MIN_DISTANCE_H
3
4#ifdef __cplusplus
5#include <cstdint>
6#include <iostream>
7#include <string>
8#include <vector>
9#endif
10
18int64_t min_dist(const std::string word1, const std::string word2) {
19 if (word1.size() == 0 && word2.size() == 0) {
20 return 0;
21 }
22 if (word1.size() == 0 && word2.size() != 0) {
23 return word2.size();
24 }
25 if (word1.size() != 0 && word2.size() == 0) {
26 return word1.size();
27 }
28 int n = word1.size(), w = word2.size();
29 std::vector<std::vector<int>> dp(n + 1, std::vector<int>(w + 1));
30 for (int i = 0; i <= n; i++) {
31 dp[i][0] = i;
32 }
33
34 for (int i = 0; i <= w; i++) {
35 dp[0][i] = i;
36 }
37 for (int i = 1; i <= n; i++) {
38 for (int j = 1; j <= w; j++) {
39 if (word1[i - 1] == word2[j - 1]) {
40 dp[i][j] = dp[i - 1][j - 1];
41 } else {
42 dp[i][j] = std::min(dp[i - 1][j - 1], std::min(dp[i - 1][j], dp[i][j - 1])) + 1;
43 }
44 }
45 }
46
47 return dp[n][w];
48}
49
50#endif