题目描述:请实现一个函数,把字符串中的每个空格替换成”%20”。
题目解析:一个空格换成%20后长度增加2,所以先统计出字符串中一共有多少个空格,假如是n个空格,那么在替换后,字符串的长度增加了2n个字符。所以从后开始遍历字符数组,遇到空格,就替换成%20。
public static char[] replace(char[] array) {
if (array == null) {
return null;
}
int spaceCount = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] == ' ') {
spaceCount++;
}
}
char[] result = new char[array.length + spaceCount * 2];
int i = array.length - 1, j = result.length - 1;
while (i >= 0 && j >= 0) {
if (array[i] == ' ') {
result[j--] = '0';
result[j--] = '2';
result[j--] = '%';
i--;
} else {
result[j--] = array[i--];
}
}
return result;
}