diff --git a/README.md b/README.md index 154648e..23f3742 100644 --- a/README.md +++ b/README.md @@ -687,6 +687,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文 ### 其它 +- [构造有效字符串的最少插入数](src/other/minimum_additions_to_make_valid_string.cpp) [Stack, Greedy, String, Dynamic Programming] + + - LeetCode 2645. 构造有效字符串的最少插入数 + - [最小体力消耗路径](src/search/path_with_minimum_effort.cpp) [深度优先搜索, 广度优先搜索, 并查集, 数组, 二分查找, 矩阵, 堆(优先队列)] - LeetCode 1631. 最小体力消耗路径 diff --git a/images/other/minimum_additions_to_make_valid_string.jpeg b/images/other/minimum_additions_to_make_valid_string.jpeg new file mode 100644 index 0000000..bd42fb8 Binary files /dev/null and b/images/other/minimum_additions_to_make_valid_string.jpeg differ diff --git a/src/other/minimum_additions_to_make_valid_string.cpp b/src/other/minimum_additions_to_make_valid_string.cpp new file mode 100644 index 0000000..e2f32fc --- /dev/null +++ b/src/other/minimum_additions_to_make_valid_string.cpp @@ -0,0 +1,18 @@ +// 构造有效字符串的最少插入数 +// https://leetcode.cn/problems/minimum-additions-to-make-valid-string +// INLINE ../../images/other/minimum_additions_to_make_valid_string.jpeg + +#include + +class Solution { +public: + int addMinimum(string word) { + int n = word.size(), cnt = 1; + for (int i = 1; i < n; i++) { + if (word[i] <= word[i - 1]) { + cnt++; + } + } + return cnt * 3 - n; + } +}; \ No newline at end of file diff --git a/test/lib/lib_test.cpp b/test/lib/lib_test.cpp index c11c5f9..d966976 100644 --- a/test/lib/lib_test.cpp +++ b/test/lib/lib_test.cpp @@ -1,4 +1,4 @@ -// 执行编译时间:2024-01-10 21:59:48 +// 执行编译时间:2024-01-11 11:49:55 #include #include diff --git a/test/other/minimum_additions_to_make_valid_string_test.cpp b/test/other/minimum_additions_to_make_valid_string_test.cpp new file mode 100644 index 0000000..d63c4d7 --- /dev/null +++ b/test/other/minimum_additions_to_make_valid_string_test.cpp @@ -0,0 +1,28 @@ +#include + +TEST(构造有效字符串的最少插入数, addMinimum) { + Solution solution; + // 示例 1: + // 输入:word = "b" + // 输出:2 + // 解释:在 "b" 之前插入 "a" ,在 "b" 之后插入 "c" 可以得到有效字符串 "abc" 。 + string word = "b"; + int expected = 2; + EXPECT_EQ(solution.addMinimum(word), expected); + + // 示例 2: + // 输入:word = "aaa" + // 输出:6 + // 解释:在每个 "a" 之后依次插入 "b" 和 "c" 可以得到有效字符串 "abcabcabc" 。 + word = "aaa"; + expected = 6; + EXPECT_EQ(solution.addMinimum(word), expected); + + // 示例 3: + // 输入:word = "abc" + // 输出:0 + // 解释:word 已经是有效字符串,不需要进行修改。 + word = "abc"; + expected = 0; + EXPECT_EQ(solution.addMinimum(word), expected); +}