当前位置:网站首页>剑指 Offer 05. 替换空格
剑指 Offer 05. 替换空格
2022-06-22 20:52:00 【前端粉刷匠】
每天一算法~~, 坚持第一天。
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
范围:0 <= s 的长度 <= 10000
示例:
输入:s = "We are happy."
输出:"We%20are%20happy."
解题方法1:
思路:简单粗暴直接使用split方法,将其用空格分隔为字符串数组,然后使用join方法再转换为字符串。
function replaceSpace(s){
if(s.length > 10000) return null;
return s.split(" ").join("%20");
}
解题方法2:
思路:使用正则表达式进行替换
function replaceSpace(s){
if(s.length > 10000) return null;
return s.replace(/ /g, '%20')
}
解题方法3:
思路:循环字符串,然后判断有没有空格,如果有空格则将空格替换
function replaceSpace(s){
if(s.length > 10000) return null;
let str = ''
for (const key in s) {
if(s[key] === ' '){
str = str + '%20'
}else{
str = str + s[key]
}
}
return str;
}
目前想到这些方法。如果还有好的方法,希望大家多多分享。
Code不仅仅是年轻饭,应该是一辈子的爱好~
边栏推荐
- 2021-04-14
- Remote access and control - SSH Remote Management and TCP wrappers access control
- Solution to cache inconsistency
- Spark SQL Start(2.4.3)
- Next permutation [give play to subjective initiative to discover laws]
- Mysql8 installation and environment configuration
- Spark SQL Generic Load/Save Functions(2.4.3)
- 安装typescript环境并开启VSCode自动监视编译ts文件为js文件
- Dip1000,1 of D
- 2021-08-22
猜你喜欢
Several ways of redis persistence -- deeply parsing RDB

The mental process and understanding of visual project code design

In the third week of June, the main growth ranking list (BiliBili platform) of station B single feigua data up was released!

SOA Service Oriented Architecture

Generate detailed API and parameters of QR code using qrcodejs2
![Total number of combinations [standard backtracking + backtracking techniques -- reducing stack depth]](/img/88/3a07589bf8edab618139b1bf1680e8.png)
Total number of combinations [standard backtracking + backtracking techniques -- reducing stack depth]

Ensure database and cache consistency

In a frame because it set 'X-FRAME-OPTIONS' to' deny '

Why do you perform performance tests before the software goes online? How to find a software performance testing organization

《强化学习周刊》第50期:SafeRL-Kit、GMI-DRL、RP-SDRL & 离线元强化学习
随机推荐
Solution to cache inconsistency
Ensure database and cache consistency
SOA Service Oriented Architecture
2021-08-26
MySQL functions
Greedy interval problem (4)
SSH method 2 for adding node nodes in Jenkins
【Kubernetes 系列】Kubernetes 概述
One case of SQL performance degradation caused by modifying implicit parameters
别再用 System.currentTimeMillis() 统计耗时了,太 Low,StopWatch 好用到爆!
AutoCAD - five annotation shortcuts
《强化学习周刊》第50期:SafeRL-Kit、GMI-DRL、RP-SDRL & 离线元强化学习
2021-08-21
2021-08-21
Phantomjs utility code snippet (under continuous update...)
In the middle of the year, we will promote the integration of worry free, and the value-added package will be reduced by 6
mysql主从同步及其分库分表基本流程
Redis error reporting and common configurations
MySQL constraints
R language data preprocessing, converting type variables into factor variables, converting data sets into H2O format, and dividing data sets (training set, test set, verification set)