当前位置:网站首页>力扣.剑指offer05.替换空格
力扣.剑指offer05.替换空格
2022-07-31 05:17:00 【旺仔 小馒头】
请实现一个函数,把字符串 s
中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy." 输出:"We%20are%20happy."
思想
法一:string
创建一个string容器v,遍历字符串s,遇到空格,直接push_back依次压入字符'%' , '2' ,'0',如果是普通字符直接将其压入新容器
// 法一:用C++11里的方法
class Solution1 {
public:
string replaceSpace(string s) {
string v;
for (auto ch : s)
if (ch == ' '){
v.push_back('%');
v.push_back('2');
v.push_back('0');
}
else
v.push_back(ch);
return v;
}
};
法二:replace
利用string容器自带的方法replace
string& replace(int pos, int n, const string& str); // 替换从pos开始n个字符为字符串str
// 法二:string中自带函数replace
class Solution {
public:
string replaceSpace(string s) {
// 统计空格数量
for (int i = 0; i < s.size(); i++){
if (s[i] == ' '){
s.replace(i, 1, "%20");
// 跳过已经替换后的字符%20的位置,从后遍历
i += 2;
}
}
return s;
}
};
法三: 双指针法
// 法三:双指针原地更改,遇到' '就扩容2个空位,先把数组尺寸调到我们要大小
class Solution {
public:
string replaceSpace(string s) {
// 统计空格数量
int count = 0;
for (auto ch : s){
if (ch == ' '){
count++;
}
}
// 将字符串个数换成个s.size() + count*2,多的部分用' '来填
int oldSize = s.size();
int newSize = s.size() + count*2;
s.resize(newSize);
// 利用双指针,指针l指向原空间的最后一个位置,指针r指向新空间的最后一个位置,同时往前移动
int l = oldSize - 1;
int r = newSize - 1;
while (l < r){
if (s[l] == ' '){
s[r] = '0';
s[r-1] = '2';
s[r-2] = '%';
r -= 2;
}
else
s[r] = s[l];
r--;
l--;
}
return s;
}
};
边栏推荐
- Pytorch实现ResNet
- opencv之访问图像像素的三种方法
- Getting Started with MySQL: The Case Statement Works Well
- UR3机器人雅克比矩阵
- 安装显卡过程中遇到问题汇总
- DSPE-PEG-Thiol DSPE-PEG-SH 磷脂-聚乙二醇-巯基脂质体制备用
- Introduction to CLS-PEG-FITC Fluorescein-PEG-CLS Cholesterol-PEG-Fluorescein
- CLS-PEG-FITC Fluorescein-PEG-CLS 胆固醇-聚乙二醇-荧光素简介
- 深度学习知识点杂谈
- box-shadow相关属性
猜你喜欢
二进制转换成十六进制、位运算、结构体
C语言结构体(必须掌握版)
The solution to the IDEA console not being able to enter information
Cholesterol-PEG-Thiol CLS-PEG-SH Cholesterol-Polyethylene Glycol-Sulfhydryl
IDEA概述和安装及调试
Learn how to get a database connection with JDBC
【Rhapsody学习笔记】3:Dishwasher
Software Testing Interview Questions 2021
Cholesterol-PEG-Azide CLS-PEG-N3 Cholesterol-PEG-Azide MW:3400
Pytorch学习笔记13——Basic_RNN
随机推荐
多线程截取视频为每帧
Attention based ASR(LAS)
Cholesterol-PEG-Thiol CLS-PEG-SH 胆固醇-聚乙二醇-巯基
变分自编码器VAE实现MNIST数据集生成by Pytorch
DSPE-PEG-Thiol DSPE-PEG-SH phospholipid-polyethylene glycol-thiol liposome for later use
拒绝采样小记
实现离线文件推流成rtsp 2
Pytorch study notes 7 - processing input of multi-dimensional features
用pytorch里的children方法自定义网络
UR3机器人运动学分析之逆运动学分析
自然语言处理相关list
【Rhapsody学习笔记】3:Dishwasher
Remote file xxx is mapped to the local path xxx and can't be found. You can continue debugging....
活体检测CDCN学习笔记
Pytorch常用函数
Getting Started with MySQL: The Case Statement Works Well
UR3机器人运动学分析之正运动学分析
Cholesterol-PEG-Azide CLS-PEG-N3 Cholesterol-PEG-Azide MW:3400
2022年SQL大厂高频实战面试题(详细解析)
Rejection sampling note