diff --git a/.vscode/settings.json b/.vscode/settings.json index bba9b4a..34408de 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -194,6 +194,7 @@ "cxbc", "dbqca", "DCMAKE", + "ddinggo", "dearmour", "deque", "dlimit", diff --git a/README.md b/README.md index fc3194d..ef5aeea 100644 --- a/README.md +++ b/README.md @@ -715,6 +715,10 @@ C++标准库提供的数据结构实在是太多了,参考[C++标准库头文 ### 其它 +- [自由之路](src/search/freedom_trail.cpp) [深度优先搜索, 广度优先搜索, 字符串, 动态规划] + + - LeetCode 514. 自由之路 + - [构造有效字符串的最少插入数](src/other/minimum_additions_to_make_valid_string.cpp) [Stack, Greedy, String, Dynamic Programming] - LeetCode 2645. 构造有效字符串的最少插入数 diff --git a/images/search/freedom_trail.jpeg b/images/search/freedom_trail.jpeg new file mode 100644 index 0000000..884dc05 Binary files /dev/null and b/images/search/freedom_trail.jpeg differ diff --git a/src/search/freedom_trail.cpp b/src/search/freedom_trail.cpp new file mode 100644 index 0000000..224e381 --- /dev/null +++ b/src/search/freedom_trail.cpp @@ -0,0 +1,27 @@ +// 自由之路 +// https://leetcode.cn/problems/freedom-trail +// INLINE ../../images/search/freedom_trail.jpeg + +#include + +class Solution { +public: + int findRotateSteps(string ring, string key) { + array, 26> idx_list; + int n = ring.size(), m = key.size(), pc = ring.front() - 'a'; + for (int i = 0; i < n; ++i) + idx_list[ring[i] - 'a'].push_back(i); + vector dp(n, 0x3f3f3f3f), pre(n, 0x3f3f3f3f); + pre[0] = 0; + for (int i = 0; i < m; ++i) { + for (int idx : idx_list[key[i] - 'a']) + for (int pi : idx_list[pc]) + dp[idx] = + min(dp[idx], pre[pi] + min(abs(pi - idx), n - abs(pi - idx))); + pre = std::move(dp); + dp = vector(n, 0x3f3f3f3f); + pc = key[i] - 'a'; + } + return *min_element(pre.begin(), pre.end()) + key.size(); + } +}; \ No newline at end of file diff --git a/test/lib/lib_test.cpp b/test/lib/lib_test.cpp index 0b4f6ba..749a970 100644 --- a/test/lib/lib_test.cpp +++ b/test/lib/lib_test.cpp @@ -1,4 +1,4 @@ -// 执行编译时间:2024-01-23 10:16:33 +// 执行编译时间:2024-01-29 10:39:09 #include #include diff --git a/test/search/freedom_trail_test.cpp b/test/search/freedom_trail_test.cpp new file mode 100644 index 0000000..ff8a15d --- /dev/null +++ b/test/search/freedom_trail_test.cpp @@ -0,0 +1,22 @@ +#include + +TEST(自由之路, findRotateSteps) { + Solution solution; + // 示例 1: + // 输入: ring = "godding", key = "gd" + // 输出: 4 + // 解释: + // 对于 key 的第一个字符 'g',已经在正确的位置, 我们只需要1步来拼写这个字符。 + // 对于 key 的第二个字符 'd',我们需要逆时针旋转 ring "godding" 2步使它变成 + // "ddinggo"。 当然, 我们还需要1步进行拼写。 因此最终的输出是 4。 + string ring = "godding"; + string key = "gd"; + EXPECT_EQ(solution.findRotateSteps(ring, key), 4); + + // 示例 2: + // 输入: ring = "godding", key = "godding" + // 输出: 13 + ring = "godding"; + key = "godding"; + EXPECT_EQ(solution.findRotateSteps(ring, key), 13); +}