mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
Update
This commit is contained in:
@ -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 已经收录,欢迎star,fork,共同学习,一起进步。
|
||||
|
Reference in New Issue
Block a user