当前位置:网站首页>力扣.剑指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;
}
};边栏推荐
- MySQL 主从切换步骤
- 【Rhapsody学习笔记】2:Count Down
- 钉钉H5微应用免登鉴权
- 【Rhapsody学习笔记】1:Hello World
- DingTalk H5 micro-app login authentication
- DingTalk Enterprise Internal-H5 Micro Application Development
- Hyperparameter Optimization - Excerpt
- Learn how to get a database connection with JDBC
- DSPE-PEG-Biotin, CAS: 385437-57-0, phospholipid-polyethylene glycol-biotin prolongs circulating half-life
- 安装显卡过程中遇到问题汇总
猜你喜欢

DSPE-PEG-Thiol DSPE-PEG-SH phospholipid-polyethylene glycol-thiol liposome for later use

Cholesterol-PEG-DBCO Cholesterol-Polyethylene Glycol-Diphenylcyclooctyne Chemical Reagent

浏览器中的画中画(Picture-in-Picture)API

UR3机器人运动学分析之逆运动学分析

MW: 3400 4-Arm PEG-DSPE four-arm-polyethylene glycol-phospholipid a saturated 18-carbon phospholipid

活体检测CDCN学习笔记

DingTalk Enterprise Internal-H5 Micro Application Development

pytorch模型微调finetuning训练image_dog(kaggle)

random.randint函数用法

Pytorch每日一练——预测泰坦尼克号船上的生存乘客
随机推荐
CAS: 1403744-37-5 DSPE-PEG-FA Phospholipid-Polyethylene Glycol-Folic Acid for Scientific Research
DSPE-PEG-Azide DSPE-PED-N3 磷脂-聚乙二醇-叠氮脂质PFG
Picture-in-Picture API in the browser
科学研究用磷脂-聚乙二醇-活性酯 DSPE-PEG-NHS CAS:1445723-73-8
钉钉H5微应用免登鉴权
2022年SQL大厂高频实战面试题(详细解析)
Session和Cookie,Token
Attention based ASR(LAS)
box-shadow related properties
词向量——demo
Sourcery插件(自动提升代码质量)
Cholesterol-PEG-Acid CLS-PEG-COOH Cholesterol-Polyethylene Glycol-Carboxyl Modified Peptides
DSPE-PEG-Thiol DSPE-PEG-SH 磷脂-聚乙二醇-巯基脂质体制备用
Four common ways of POST to submit data
C语言静态变量static
机器学习和深度学习概述
应用usb_cam同时打开多个摄像头方法
【Rhapsody学习笔记】1:Hello World
Software Testing Interview Questions 2021
Introduction to CLS-PEG-FITC Fluorescein-PEG-CLS Cholesterol-PEG-Fluorescein