问题描述
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = “We are happy.”
输出:“We%20are%20happy.”
分析和实现
暴力实现
最容易想到的就是遍历并且进行字符串拼接,具体代码如下:
class Solution {
public String replaceSpace(String s) {
String result = "";
int length = s.length();
for(int i=length-1; i>=0; i--){
char temp = s.charAt(i);
if(temp != ' '){
result = String.valueOf(temp) + result;
}else{
result = "%20" + result;
}
}
return result;
}
}
这种方式的缺点也是非常明显的,因为字符串的拼接耗时是很大的。
辅助数组
按照用空间换时间的思路,对上述的方法进行改进。
- 因为遇到空格之后,一个空格会变成三倍长,所以可以使用一个三倍长的 char 数组来装入改变之后的内容。
- 字符串的初始化方法,可以直接放入 char 数组进行初始化, 具体使用方法如下:
Char[] array = new Char[10];
// offset 是 array 的开始下标
// count 是从 array 开始数 count 个字符
String s = new String(array, offset, count);
平常字符串总是初始化为空,已经忘记这种初始化方法了,这次算是学习到了。
class Solution {
public String replaceSpace(String s) {
int length = s.length();
char[] temp = new char[length * 3];
int resultLength = 0;
for(int i=0;i<s.length(); i++){
if(s.charAt(i) == ' '){
temp[resultLength++] = '%';
temp[resultLength++] = '2';
temp[resultLength++] = '0';
}else{
temp[resultLength++] = s.charAt(i);
}
}
String result = new String(temp, 0, resultLength);
return result;
}
}