当前位置:网站首页>剑指Offer05. 替换空格
剑指Offer05. 替换空格
2022-07-03 11:50:00 【伍六琪】
剑指Offer05. 替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
JAVA代码
工具类方法
在这里列举一下,但是不可以投机取巧哦~~
class Solution {
public String replaceSpace(String s) {
return s.replace(" ","%20");
}
}

官方办法
通过将字符串转为字符数组的方法,逐个字符分析该字符串,如果是空格就向数组中插入% 2 0 三个字符,如果不是空格就将该位置字符直接插入数组中。
注意:不能直接arr.toString()转为字符串,会乱码。
new String(源头数组,起始位置,终止位置)
class Solution {
public String replaceSpace(String s) {
char[] arr = new char[s.length()*3];
int index = 0;
for(int i = 0;i<s.length();i++){
if(s.charAt(i)==' '){
arr[index++] = '%';
arr[index++] = '2';
arr[index++] = '0';
}else{
arr[index++] = s.charAt(i);
}
}
String newStr = new String(arr,0,index);
return newStr;
}
}
解决问题的思路非常重要。
边栏推荐
- 347. Top k high frequency elements
- init. RC service failed to start
- 023 ([template] minimum spanning tree) (minimum spanning tree)
- Basic knowledge of OpenGL (sort it out according to your own understanding)
- ES6 standard
- Optimize interface performance
- LeetCode 0556. Next bigger element III - end of step 4
- temp
- Wechat applet development - page Jump transfer parameters
- Flutter 退出登录二次确认怎么做才更优雅?
猜你喜欢

(构造笔记)ADT与OOP

Shutter: add gradient stroke to font

Basic knowledge of OpenGL (sort it out according to your own understanding)

Shardingsphere sub database and sub table < 3 >

Qt+vtk+occt reading iges/step model

Quantitative calculation research

Flutter 退出登录二次确认怎么做才更优雅?

Develop plug-ins for idea

Wechat applet - basic content

Socket TCP for network communication (I)
随机推荐
Fundamentals of concurrent programming (III)
Summary of development issues
Is it OK to open an account for online stock speculation? Is the fund safe?
Download address and installation tutorial of vs2015
Php Export word method (One MHT)
Dart: about Libraries
[learning notes] DP status and transfer
【附下载】密码获取工具LaZagne安装及使用
102. Sequence traversal of binary tree
239. Sliding window maximum
Lambda expression
02_ Lock the code, and don't let the "lock" become a worry
Basic knowledge of OpenGL (sort it out according to your own understanding)
Slf4j log facade
Systemverilog-- OOP--对象的拷贝
PHP get the file list and folder list under the folder
OpenGL draws colored triangles
Socket TCP for network communication (I)
在网上炒股开户可以吗?资金安全吗?
Unicode查询的官方网站