-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cpp
More file actions
51 lines (47 loc) · 1.34 KB
/
Solution.cpp
File metadata and controls
51 lines (47 loc) · 1.34 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
//
// Created by Ruizhe Hou on 2020/9/26.
//
#include <vector>
#include <string>
using namespace std;
class Solution {
public:
/**
* @param words: a set of stirngs
* @param target: a target string
* @param k: An integer
* @return: output all the strings that meet the requirements
*/
int minDistance(string word1, string word2, int k) {
int m = word1.size();
int n = word2.size();
if (m - n > k || n - m > k) return k + 1;
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
for (int i = 0; i <= m; i++) {
dp[i][0] = i;
}
for (int j = 0; j <= n; j++) {
dp[0][j] = j;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (word1[i - 1] == word2[j - 1])
dp[i][j] = dp[i - 1][j - 1];
else {
dp[i][j] = 1 + min(dp[i - 1][j - 1], min(dp[i][j - 1], dp[i - 1][j]));
}
}
}
return dp[m][n];
}
vector<string> kDistance(vector<string> &words, string &target, int k) {
// write your code here
vector<string> res;
for (auto &word: words) {
if (minDistance(word, target, k) <= k) {
res.push_back(word);
}
}
return res;
}
};