当前位置:网站首页>Leetcode——剑指 Offer 05. 替换空格
Leetcode——剑指 Offer 05. 替换空格
2022-07-07 12:15:00 【styfish】
概述
分析
这题,如果不限制空间复杂度,其实很简单,直接开一个新的
string
就可以实现了但是,如果要求只能原理处理呢?这里有一个问题需要解决:
s --> %20
,增加了字符,需要增加striing的容量因为
push_back
之能最末尾操作
思路
增加容量
- 可以先遍历一遍string,统计空格的个数,就可以知道最终需要扩充的大小了
- 然后利用
resize()
来扩充大小
代码
class Solution {
public:
string replaceSpace(string s) {
int count = 0; // 统计空格的个数
int sOldSize = s.size();
for (int i = 0; i < s.size(); i++) {
if (s[i] == ' ') {
count++;
}
}
// 扩充字符串s的大小,也就是每个空格替换成"%20"之后的大小
s.resize(s.size() + count * 2);
// 为了原地操作,所以使用双指针法
int ptr = s.size() - 1, wokr_ptr = sOldSize - 1;
// 这里要从后往前,因为如果添加新元素从前往后,会覆盖掉原始的元素(
for(; wokr_ptr >= 0; --wokr_ptr) {
if (s[wokr_ptr] != ' ') s[ptr--] = s[wokr_ptr];
else {
s[ptr] = '0';
s[ptr - 1] = '2';
s[ptr - 2] = '%';
ptr -= 3;
}
}
return s;
}
};
边栏推荐
- WPF DataGrid realizes the UI interface to respond to a data change in a single line
- Introduction to sakt method
- Cargo placement problem
- Laravel Form-builder使用
- 請問,在使用flink sql sink數據到kafka的時候出現執行成功,但是kafka裏面沒有數
- 杭电oj2092 整数解
- [high frequency interview questions] difficulty 2.5/5, simple combination of DFS trie template level application questions
- 请问指南针股票软件可靠吗?交易股票安全吗?
- UML 顺序图(时序图)
- call undefined function openssl_ cipher_ iv_ length
猜你喜欢
Help tenants
XML文件的解析操作
2022-7-6 sigurg is used to receive external data. I don't know why it can't be printed out
Did login metamask
TPG x AIDU | AI leading talent recruitment plan in progress!
The longest ascending subsequence model acwing 1012 Sister cities
GVIM [III] [u vimrc configuration]
"Song of ice and fire" in the eleventh issue of "open source Roundtable" -- how to balance the natural contradiction between open source and security?
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf
Take you to master the three-tier architecture (recommended Collection)
随机推荐
mysql导入文件出现Data truncated for column ‘xxx’ at row 1的原因
[untitled]
IP address home location query full version
Cesium 已知一点经纬度和距离求另一个点的经纬度
高等数学---第八章多元函数微分学1
UML 顺序图(时序图)
ES日志报错赏析-Limit of total fields
Vscode configuration uses pylint syntax checker
UML sequence diagram (sequence diagram)
UML 状态图
PC端页面如何调用QQ进行在线聊天?
Clickhouse (03) how to install and deploy Clickhouse
常用数字信号编码之反向不归零码码、曼彻斯特编码、差分曼彻斯特编码
交换机和路由器的异同
Vmware共享主机的有线网络IP地址
常用數字信號編碼之反向不歸零碼碼、曼徹斯特編碼、差分曼徹斯特編碼
最长上升子序列模型 AcWing 1014. 登山
Laravel5 call to undefined function OpenSSL cipher IV length() error php7 failed to open OpenSSL extension
Arm cortex-a9, mcimx6u7cvm08ad processor application
How does MySQL control the number of replace?