2707. 字符串中的额外字符

2707. 字符串中的额外字符

解法一: 动态规划

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
class Solution {
public int minExtraChar(String s, String[] dictionary) {
int n = s.length();
int[] dp = new int[n + 1];
for (int i = 0; i < n; i++) {
dp[i + 1] = dp[i] + 1;
for (String word : dictionary) {
if (this.isSameFromLast(s, i, word)) {
dp[i + 1] = Math.min(dp[i + 1], dp[i - word.length() + 1]);
}
}
}
return dp[n];
}

private boolean isSameFromLast(String str, int endIndex, String subStr) {
int n1 = str.length();
int n2 = subStr.length();
if (n2 > endIndex + 1) {
return false;
}
int i = endIndex;
int j = n2 - 1;
while (j >= 0) {
if (str.charAt(i) != subStr.charAt(j)) {
return false;
}
i--;
j--;
}
return true;
}

}

解法二: 前缀树

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
class Solution {

public static class Trie {

private Trie[] tries;

private boolean isEnd;

public Trie() {
this.tries = new Trie[26];
this.isEnd = false;
}

public void insert(String word) {
int n = word.length();
Trie trie = this;
for (int i = 0; i < n; i++) {
int j = word.charAt(i) - 'a';
if (trie.tries[j] == null) {
trie.tries[j] = new Trie();
}
trie = trie.tries[j];
}
trie.isEnd = true;
}

public Trie track(char ch) {
return tries[ch - 'a'];
}

public boolean isEnd() {
return isEnd;
}

}

public int minExtraChar(String s, String[] dictionary) {
Trie root = new Trie();
for (String word : dictionary) {
StringBuilder sb = new StringBuilder(word);
root.insert(sb.reverse().toString());
}
int n = s.length();
int[] dp = new int[n + 1];
for (int i = 0; i < n; i++) {
dp[i + 1] = dp[i] + 1;
Trie trie = root;
for (int j = i; j >= 0; j--) {
trie = trie.track(s.charAt(j));
if (trie == null) {
break;
}
if (trie.isEnd()) {
dp[i + 1] = Math.min(dp[i + 1], dp[j]);
}
}
}
return dp[n];
}

}
作者

wuhunyu

发布于

2024-01-09

更新于

2024-01-09

许可协议