当前位置:网站首页>剑指 Offer 05. 替换空格
剑指 Offer 05. 替换空格
2022-07-25 05:26:00 【智慧的人不要秃头】
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。

方法一:申请额外空间
class Solution {
public:
//思想:创建一个新的字符串作为返回的结果,遍历字符串,如果遇到' ',就追加“%20”,如果非' ',就追加遍历到的字符
string replaceSpace(string s) {
string res = "";
for(auto ch : s){
if(ch == ' '){
res += "%20";
}
else{
res += ch;
}
}
return res;
}
};
//时间复杂度:O(N)遍历字符串。
//空间复杂度:O(N)新创建了一个string类型的额外空间。方法二:原地修改
class Solution {
public:
//1. 初始化:空格数量 count ,字符串 s 的长度 len ;
//2. 统计空格数量:遍历 s ,遇空格则 count++ ;
//3. 修改 s 长度:添加完 "%20" 后的字符串长度应为 len + 2 * count ;
//4. 倒序遍历修改:i 指向原字符串尾部元素, j 指向新字符串尾部元素;当 i = j 时跳出(代表左方已没有空格,无需继续遍历);
//当 s[i] 不为空格时:执行 s[j] = s[i] ;
//当 s[i] 为空格时:将字符串闭区间 [j-2, j] 的元素修改为 "%20" ;由于修改了 3 个元素,因此需要 j -= 2 ;
//5. 返回值:已修改的字符串 s ;
string replaceSpace(string s) {
int count = 0; //用来统计空格的个数
int len = s.size();
//统计字符串中空格的个数
for(char c : s) {
if(c == ' ') {
count++;
}
}
//修改原字符串的长度
s.resize(len + 2 * count);
//倒序遍历修改
//用 i 来倒序遍历原字符串,用 j 来倒序遍历扩容后的字符串
for(int i = len - 1, j = s.size() - 1; i < j; i--,j--) {
if(s[i] != ' '){
s[j] = s[i];
}
else{
s[j - 2] = '%';
s[j - 1] = '2';
s[j] = '0';
j -= 2;
}
}
return s;
}
//时间复杂度 O(N) : 遍历统计、遍历修改皆使用 O(N) 时间。
//空间复杂度 O(1) : 由于是原地扩展 s 长度,因此使用 O(1) 额外空间。
};
边栏推荐
- STL notes (IV): String
- Project management tools - project developer tools
- 龙蜥社区发布首个 Anolis OS 安全指南 为用户业务系统保驾护航
- 深圳随到随考,科目四随到随考,科三理论第二理论随到随考说明
- LCP插件创建对等VLAN接口
- 2022-07-24:以下go语言代码输出什么?A:[]int{};B:[]int(nil);C:panic;D:编译错误。 package main import ( “fmt“ ) f
- Forwarding and sharing function of wechat applet
- Project management tool - Introduction and practice of Alibaba cloud projex
- Summary of common attributes of flex layout
- systemverilog中function和task区别
猜你喜欢
随机推荐
C编程 --“最大子数组的和” 的动态规划的解法
Delivery practice of private PAAS platform based on cloud native
微服务 - 远程调用(Feign组件)
STL notes (VI): container vector
Anshi semiconductor management paid a visit to Wentai technology and Gree Electric appliance
Bypass XSS filters in Web Applications
批量下载视频小技巧
LCP plug-in creates peer VLAN interface
Pikachu vulnerability platform exercise
Game 302 of leetcode
Nexttick principle analysis
Which website is suitable for physical server
ping命令
微信小程序相关操作示例
Preliminary understanding of Panda3D particle system
Typera+picgo+ Alibaba cloud OSS setup and error reporting solution [reprint]
Airserver 7.3.0 Chinese version mobile device wireless transmission computer screen tool
How to judge whether it is attacked by DDoS
接口幂等性
Arm PWN basic tutorial








