From e37f2531d7832183a75e9b2dff42aedd7b48bcca Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Tue, 29 Nov 2022 20:26:23 +0800 Subject: [PATCH] Substitute Spaces --- include/offer_05.hpp | 13 +++++++++++++ notes/src/SUMMARY.md | 4 ++++ notes/src/substitute_spaces.md | 15 +++++++++++++++ src/offer_05.cpp | 24 ++++++++++++++++++++++++ tests/offer_05.cpp | 10 ++++++++++ 5 files changed, 66 insertions(+) create mode 100644 include/offer_05.hpp create mode 100644 notes/src/substitute_spaces.md create mode 100644 src/offer_05.cpp create mode 100644 tests/offer_05.cpp diff --git a/include/offer_05.hpp b/include/offer_05.hpp new file mode 100644 index 0000000..3b4976c --- /dev/null +++ b/include/offer_05.hpp @@ -0,0 +1,13 @@ +#ifndef OFFER_05_HPP +#define OFFER_05_HPP + +#include + +using namespace std; + +class Solution { + public: + string replaceSpace(string s); +}; + +#endif diff --git a/notes/src/SUMMARY.md b/notes/src/SUMMARY.md index af4619f..3213214 100644 --- a/notes/src/SUMMARY.md +++ b/notes/src/SUMMARY.md @@ -4,6 +4,10 @@ - [移除元素](./remove_elements.md) - [长度最小的子数组](./minimum_size_subarray_sum.md) +# 字符串 + +- [替换空格](./substitute_spaces.md) + # 经典代码 - [合并两个有序链表](./merge_two_sorted_linked_lists.md) diff --git a/notes/src/substitute_spaces.md b/notes/src/substitute_spaces.md new file mode 100644 index 0000000..75956f8 --- /dev/null +++ b/notes/src/substitute_spaces.md @@ -0,0 +1,15 @@ +# 替换空格 + +[Leetcode](https://leetcode.cn/problems/ti-huan-kong-ge-lcof/) + +请实现一个函数,把字符串 s 中的每个空格替换成"%20"。 + +示例 1: + +> 输入:s = "We are happy." +> +> 输出:"We%20are%20happy." + +![demo](https://tva1.sinaimg.cn/large/e6c9d24ely1go6qmevhgpg20du09m4qp.gif) + +对于很多数组填充类问题,都可以先计算出扩展后数组的长度,然后从后往前双指针。 diff --git a/src/offer_05.cpp b/src/offer_05.cpp new file mode 100644 index 0000000..86d9b1a --- /dev/null +++ b/src/offer_05.cpp @@ -0,0 +1,24 @@ +#include "offer_05.hpp" + +string Solution::replaceSpace(string s) { + int len = s.length(); + int cnt{0}; + for (int i{0}; i < len; ++i) { + if (s[i] == ' ') { + s.push_back(' '); + s.push_back(' '); + cnt++; + } + } + len = s.length(); + for (int fast = len - 1, slow = len - 1 - 2 * cnt; fast >= 0; --slow) { + if (s[slow] == ' ') { + s[fast--] = '0'; + s[fast--] = '2'; + s[fast--] = '%'; + } else { + s[fast--] = s[slow]; + } + } + return s; +} diff --git a/tests/offer_05.cpp b/tests/offer_05.cpp new file mode 100644 index 0000000..cb83dc0 --- /dev/null +++ b/tests/offer_05.cpp @@ -0,0 +1,10 @@ +#include "offer_05.hpp" + +#include + +TEST(Offer05, Case1) { + string s{"We are happy."}; + string expected{"We%20are%20happy."}; + Solution solution; + EXPECT_EQ(solution.replaceSpace(s), expected); +}