Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

 

History

History
History
36 lines (36 loc) · 1.49 KB

File metadata and controls

36 lines (36 loc) · 1.49 KB
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* @author LZD 2019/01/31
*/
package String;
/*
* 链接:https://www.nowcoder.com/questionTerminal/4060ac7e3e404ad1a894ef3e17650423
* 来源:牛客网
* 解答者:村上挪威
* 问题1:替换字符串,是在原来的字符串上做替换,还是新开辟一个字符串做替换!
* 问题2:在当前字符串替换,怎么替换才更有效率(不考虑java里现有的replace方法)。
*      从前往后替换,后面的字符要不断往后移动,要多次移动,所以效率低下
*      从后往前,先计算需要多少空间,然后从后往前移动,则每个字符只为移动一次,这样效率更高一点。
*/
public class replaceSolution {
public String replaceSpace(StringBuffer str) {
int spacenum = 0;//spacenum为计算空格数
for(int i=0;i<str.length();i++){
if(str.charAt(i)==' ')
spacenum++;
}
int indexold = str.length()-1; //indexold为为替换前的str下标
int newlength = str.length() + spacenum*2;//计算空格转换成%20之后的str长度
int indexnew = newlength-1;//indexold为为把空格替换为%20后的str下标
str.setLength(newlength);//使str的长度扩大到转换成%20之后的长度,防止下标越界
for(;indexold>=0 && indexold<newlength;--indexold){
if(str.charAt(indexold) == ' '){
str.setCharAt(indexnew--, '0');
str.setCharAt(indexnew--, '2');
str.setCharAt(indexnew--, '%');
}else{
str.setCharAt(indexnew--, str.charAt(indexold));
}
}
return str.toString();
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.