Skip to content

Commit b52511c

Browse files
committed
add: 构造有效字符串的最少插入数
1 parent b55bed5 commit b52511c

5 files changed

+51
-1
lines changed

README.md

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

688688
### 其它
689689

690+
- [构造有效字符串的最少插入数](src/other/minimum_additions_to_make_valid_string.cpp) [Stack, Greedy, String, Dynamic Programming]
691+
692+
- LeetCode 2645. 构造有效字符串的最少插入数 <https://leetcode.cn/problems/minimum-additions-to-make-valid-string>
693+
690694
- [最小体力消耗路径](src/search/path_with_minimum_effort.cpp) [深度优先搜索, 广度优先搜索, 并查集, 数组, 二分查找, 矩阵, 堆(优先队列)]
691695

692696
- LeetCode 1631. 最小体力消耗路径 <https://leetcode.cn/problems/path-with-minimum-effort>
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// 构造有效字符串的最少插入数
2+
// https://leetcode.cn/problems/minimum-additions-to-make-valid-string
3+
// INLINE ../../images/other/minimum_additions_to_make_valid_string.jpeg
4+
5+
#include <headers.hpp>
6+
7+
class Solution {
8+
public:
9+
int addMinimum(string word) {
10+
int n = word.size(), cnt = 1;
11+
for (int i = 1; i < n; i++) {
12+
if (word[i] <= word[i - 1]) {
13+
cnt++;
14+
}
15+
}
16+
return cnt * 3 - n;
17+
}
18+
};

test/lib/lib_test.cpp

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// 执行编译时间:2024-01-10 21:59:48
1+
// 执行编译时间:2024-01-11 11:49:55
22
#include <gtest/gtest.h>
33
#include <lib.hpp>
44

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#include <other/minimum_additions_to_make_valid_string.cpp>
2+
3+
TEST(构造有效字符串的最少插入数, addMinimum) {
4+
Solution solution;
5+
// 示例 1:
6+
// 输入:word = "b"
7+
// 输出:2
8+
// 解释:在 "b" 之前插入 "a" ,在 "b" 之后插入 "c" 可以得到有效字符串 "abc" 。
9+
string word = "b";
10+
int expected = 2;
11+
EXPECT_EQ(solution.addMinimum(word), expected);
12+
13+
// 示例 2:
14+
// 输入:word = "aaa"
15+
// 输出:6
16+
// 解释:在每个 "a" 之后依次插入 "b" 和 "c" 可以得到有效字符串 "abcabcabc" 。
17+
word = "aaa";
18+
expected = 6;
19+
EXPECT_EQ(solution.addMinimum(word), expected);
20+
21+
// 示例 3:
22+
// 输入:word = "abc"
23+
// 输出:0
24+
// 解释:word 已经是有效字符串,不需要进行修改。
25+
word = "abc";
26+
expected = 0;
27+
EXPECT_EQ(solution.addMinimum(word), expected);
28+
}

0 commit comments

Comments
 (0)