题目:请实现一个函数,把字符串 s 中的每个空格替换成"%20"
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
方法一:
- 直接使用java内部方法
- 用的StringBuffer,效率略低
public String replaceSpace(String s) {
// 用的StringBuffer,效率略低
return s.replaceAll(" ", "%20");
}
方法二:
- 遍历每个字符,逐个替换
- 时间复杂度:O(n)O(n)。遍历字符串 s 一遍
- 空间复杂度:O(n)O(n)。额外创建字符数组,长度为 s 的长度的 3 倍
public String replaceSpace(String s) {
int length = s.length();
char[] array = new char[length * 3];
int size = 0;
for (int i = 0; i < length; i++) {
char c = s.charAt(i);
if (c == ' ') {
array[size++] = '%';
array[size++] = '2';
array[size++] = '0';
} else {
array[size++] = c;
}
}
return new String(array, 0, size);
}
方法三:
- 遍历每个字符,逐个替换
- 使用StringBuilder
public String replaceSpace(String s) {
StringBuilder stringBuilder = new StringBuilder();
for (char c: s.toCharArray()) {
if (c == ' ') {
stringBuilder.append("%20");
} else {
stringBuilder.append(c);
}
}
return stringBuilder.toString();
}
方法四:
- 用空格切分成字符串数组
- 用%20连接数组的每个元素
public String replaceSpace(String s) {
StringBuilder stringBuilder = new StringBuilder();
String[] array = s.split(" ");
for (int i = 0; i < array.length; i++) {
if (i != array.length - 1) {
stringBuilder.append(array[i]).append("%20");
continue;
}
stringBuilder.append(array[i]);
}
return stringBuilder.toString();
}
Test
@Test
public void testReplaceSpace() {
Algorithm algorithm = new Algorithm();
String s = "We are happy.";
Long start1 = System.nanoTime();
System.out.println(algorithm.replaceSpace(s));
Long end1 = System.nanoTime();
System.out.println("time used: " + (end1 - start1));
System.out.println("===============================================");
Long start2 = System.nanoTime();
System.out.println(algorithm.replaceSpace2(s));
Long end2 = System.nanoTime();
System.out.println("time used: " + (end2 - start2));
System.out.println("===============================================");
Long start3 = System.nanoTime();
System.out.println(algorithm.replaceSpace3(s));
Long end3 = System.nanoTime();
System.out.println("time used: " + (end3 - start3));
System.out.println("===============================================");
Long start4 = System.nanoTime();
System.out.println(algorithm.replaceSpace4(s));
Long end4 = System.nanoTime();
System.out.println("time used: " + (end4 - start4));
}
结果
We%20are%20happy.
time used: 95500
===============================================
We%20are%20happy.
time used: 20400
===============================================
We%20are%20happy.
time used: 24800
===============================================
We%20are%20happy.
time used: 349900