当前位置:网站首页>剑指 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不仅仅是年轻饭,应该是一辈子的爱好~
边栏推荐
- The breakthrough of key chips hindering Huawei 5g mobile phones has been achieved, and domestic chips have gained 10% share
- Spark SQL Generic Load/Save Functions(2.4.3)
- Business stability construction ideas based on Cloud Architecture
- Spark SQL Generic Load/Save Functions(2.4.3)
- Atcoder abc256 full problem solution (interval merging template, matrix fast power optimization DP, line segment tree...)
- C language -- 17 function introduction
- js----SVG转PNG
- 获取当前所在周的起始和结束的日期
- SourceTree版本管理常用操作
- 2021-03-06
猜你喜欢

The mental process and understanding of visual project code design

Reasons for the failure of digital transformation and the way to success

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

c# sqlsugar,hisql,freesql orm框架全方位性能测试对比 sqlserver 性能测试

Do domestic mobile phones turn apples? It turned out that it was realized by 100 yuan machine and sharp price reduction

2021-08-21
Task cache compilation caused by gradle build cache

【Kubernetes 系列】Kubernetes 概述

LinkedList source code analysis
Summary of transport layer knowledge points
随机推荐
Dip1000,1 of D
Greedy interval problem (2)
2021-08-26
A group of K overturned linked lists [disassembly / overturning / assembly of linked lists]
How to manage tasks in note taking software such as flowus and notation?
为 localStorage 添加过期时间
Generate detailed API and parameters of QR code using qrcodejs2
Lua-- use of data types, variables, loops, functions and operators
Task cache compilation caused by gradle build cache
The method of making videos of knowledge payment system support m3u8 format playback
Seriously, the hang up of the kotlin collaboration process is not so mysterious (principle)
Grafana report display of sentinel based high availability current limiting system
Using the hbuilder x editor to install a solution for terminal window plug-ins that are not responding
What if the SQL execution plan of the production system suddenly becomes worse?
Delphi SOAP WebService 服务器端多个 SoapDataModule 要注意的问题
js读取剪切板的图片
The relationship between derivative and differential of function
2021-04-14
SSH method 2 for adding node nodes in Jenkins
2021-04-05