Skip to content

Commit c8697ce

Browse files
committed
add: 字符串中的额外字符
1 parent 3315b40 commit c8697ce

File tree

6 files changed

+56
-1
lines changed

6 files changed

+56
-1
lines changed

.vscode/settings.json

+2
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@
213213
"LDFLAGS",
214214
"leetcode",
215215
"leetcoded",
216+
"leetscode",
216217
"libc",
217218
"logn",
218219
"loveleetcode",
@@ -236,6 +237,7 @@
236237
"repost",
237238
"Repunit",
238239
"RXXLRXRXL",
240+
"sayhelloworld",
239241
"STARTF",
240242
"STARTUPINFO",
241243
"STREQ",

README.md

+4
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文
463463

464464
###
465465

466+
- [字符串中的额外字符](src/tree/extra_characters_in_a_string.cpp) [字典树, 数组, 哈希表, 字符串, 动态规划]
467+
468+
- LeetCode 2707. 字符串中的额外字符 <https://leetcode.cn/problems/extra-characters-in-a-string>
469+
466470
- [从二叉搜索树到更大和树](src/tree/binary_search_tree_to_greater_sum_tree.cpp) [树, 深度优先搜索, 二叉搜索树, 二叉树]
467471

468472
- LeetCode 1038. 从二叉搜索树到更大和树 <https://leetcode.cn/problems/binary-search-tree-to-greater-sum-tree>
100 KB
Loading
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// 字符串中的额外字符
2+
// https://leetcode.cn/problems/extra-characters-in-a-string
3+
// INLINE ../../images/tree/extra_characters_in_a_string.jpeg
4+
5+
#include <headers.hpp>
6+
7+
class Solution {
8+
public:
9+
int minExtraChar(string s, vector<string> &dictionary) {
10+
int n = s.size();
11+
vector<int> d(n + 1, INT_MAX);
12+
unordered_map<string, int> mp;
13+
for (auto s : dictionary) {
14+
mp[s]++;
15+
}
16+
d[0] = 0;
17+
for (int i = 1; i <= n; i++) {
18+
d[i] = d[i - 1] + 1;
19+
for (int j = i - 1; j >= 0; j--) {
20+
if (mp.count(s.substr(j, i - j))) {
21+
d[i] = min(d[i], d[j]);
22+
}
23+
}
24+
}
25+
return d[n];
26+
}
27+
};

test/lib/lib_test.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// 执行编译时间:2024-01-08 10:56:03
1+
// 执行编译时间:2024-01-09 10:59:06
22
#include <gtest/gtest.h>
33
#include <lib.hpp>
44

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
#include <tree/extra_characters_in_a_string.cpp>
2+
3+
TEST(字符串中的额外字符, minExtraChar) {
4+
Solution solution;
5+
// 示例 1:
6+
// 输入:s = "leetscode", dictionary = ["leet","code","leetcode"]
7+
// 输出:1
8+
// 解释:将 s 分成两个子字符串:下标从 0 到 3 的 "leet" 和下标从 5 到 8 的
9+
// "code" 。只有 1 个字符没有使用(下标为 4),所以我们返回 1 。
10+
string s = "leetscode";
11+
vector<string> dictionary = {"leet", "code", "leetcode"};
12+
EXPECT_EQ(solution.minExtraChar(s, dictionary), 1);
13+
14+
// 示例 2:
15+
// 输入:s = "sayhelloworld", dictionary = ["hello","world"]
16+
// 输出:3
17+
// 解释:将 s 分成两个子字符串:下标从 3 到 7 的 "hello" 和下标从 8 到 12 的
18+
// "world" 。下标为 0 ,1 和 2 的字符没有使用,所以我们返回 3 。
19+
s = "sayhelloworld";
20+
dictionary = {"hello", "world"};
21+
EXPECT_EQ(solution.minExtraChar(s, dictionary), 3);
22+
}

0 commit comments

Comments
 (0)