This commit is contained in:
youngyangyang04
2020-07-11 18:10:13 +08:00
parent c6be40e8e1
commit 5ea886f0d8
4 changed files with 16 additions and 8 deletions

View File

@ -1,16 +1,22 @@
## 题目地址
https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof/
## 思路
如果想把这道题目做到极致,就不要只用额外的辅助空间,先扩充数组到每个空格替换成"%20"之后的大小
然后从后向前替换空格
然后从后向前替换空格,双指针法:
思路如下:
<video src="../video/替换空格.mp4" controls="controls" width="640" height="320" autoplay="autoplay">
Your browser does not support the video tag.
</video>
时间复杂度空间复杂度均超过100%的用户
<img src='../pics/剑指Offer05.替换空格.png' width=600> </img></div>
## C++代码
时间复杂度空间复杂度均超过100%的用户
```
class Solution {
@ -23,10 +29,11 @@ public:
count++;
}
}
s.resize(s.size() + count * 2); // 扩充字符串s的大小也就是每个空格替换成"%20"之后的大小
// 扩充字符串s的大小也就是每个空格替换成"%20"之后的大小
s.resize(s.size() + count * 2);
int sNewSize = s.size();
// 从后先前将空格替换为"%20"
for (int i = sNewSize - 1, j = sOldSize - 1; i >= 0, j >= 0; i--, j--) {
for (int i = sNewSize - 1, j = sOldSize - 1; j < i; i--, j--) {
if (s[j] != ' ') {
s[i] = s[j];
} else {
@ -39,5 +46,6 @@ public:
return s;
}
};
```
> 笔者在先后在腾讯和百度从事技术研发多年利用工作之余重刷leetcode本文 [GitHub](https://github.com/youngyangyang04/leetcode-master )https://github.com/youngyangyang04/leetcode-master 已经收录欢迎starfork共同学习一起进步。