-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathKEditDistance.java
78 lines (70 loc) · 2.48 KB
/
KEditDistance.java
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
class TrieNode {
// Initialize your data structure here.
public TrieNode[] children;
public boolean hasWord;
public String str;
// Initialize your data structure here.
public TrieNode() {
children = new TrieNode[26];
for (int i = 0; i < 26; ++i)
children[i] = null;
hasWord = false;
}
// Adds a word into the data structure.
static public void addWord(TrieNode root, String word) {
TrieNode now = root;
for(int i = 0; i < word.length(); i++) {
Character c = word.charAt(i);
if (now.children[c - 'a'] == null) {
now.children[c - 'a'] = new TrieNode();
}
now = now.children[c - 'a'];
}
now.str = word;
now.hasWord = true;
}
}
public class Solution {
/**
* @param words a set of stirngs
* @param target a target string
* @param k an integer
* @return output all the strings that meet the requirements
*/
public List<String> kDistance(String[] words, String target, int k) {
// Write your code here
TrieNode root = new TrieNode();
for (int i = 0; i < words.length; i++)
TrieNode.addWord(root, words[i]);
List<String> result = new ArrayList<String>();
int n = target.length();
int[] dp = new int[n + 1];
for (int i = 0; i <= n; ++i)
dp[i] = i;
find(root, result, k, target, dp);
return result;
}
public void find(TrieNode node, List<String> result, int k, String target, int[] dp) {
int n = target.length();
// dp[i] 表示从Trie的root节点走到当前node节点,形成的Prefix
// 和 target的前i个字符的最小编辑距离
if (node.hasWord && dp[n] <= k) {
result.add(node.str);
}
int[] next = new int[n + 1];
for (int i = 0; i <= n; ++i)
next[i] = 0;
for (int i = 0; i < 26; ++i)
if (node.children[i] != null) {
next[0] = dp[0] + 1;
for (int j = 1; j <= n; j++) {
if (target.charAt(j - 1) - 'a' == i) {
next[j] = Math.min(dp[j - 1], Math.min(next[j - 1] + 1, dp[j] + 1));
} else {
next[j] = Math.min(dp[j - 1] + 1, Math.min(next[j - 1] + 1, dp[j] + 1));
}
}
find(node.children[i], result, k, target, next);
}
}
}