面试题5:替换空格
题目:请实现一个函数,把字符串中的每个空格替换成“%20”,例如,输入“We are happy.”,则输入“We%20are%20happy.”
import java.util.Arrays;
public class ReplaceSpaces {
private static char[] cc;
private static char[] string;
private static boolean ReplaceBlank(char[] cc, int length) {
if (string == null || length <= 0) {
return false;
}
int originalLength = string.length;
int numberOfBlank = 0;
int i = 0;
while (cc[i] != '.') {
if (cc[i] == ' ') {
numberOfBlank++;
}
i++;
}
int newLength = originalLength + numberOfBlank * 2;
System.out.println(newLength);
if (newLength > length) {
return false;
}
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal) {
if (cc[indexOfOriginal] == ' ') {
cc[indexOfNew--] = '0';
cc[indexOfNew--] = '2';
cc[indexOfNew--] = '%';
} else {
cc[indexOfNew--] = cc[indexOfOriginal];
}
indexOfOriginal--;
}
return true;
}
public static void main(String[] args) {
//ReplaceBlank(string,12);
String ss = "We are happy.";
string = ss.toCharArray();
cc = Arrays.copyOf(string, 20);
System.out.println(Arrays.toString(cc));
if (ReplaceBlank(cc, 20)) {
System.out.println(Arrays.toString(cc));
}
}
}
运行结果:
[W, e, , a, r, e, , h, a, p, p, y, ., , , , , , , ]
[W, e, %, 2, 0, a, r, e, %, 2, 0, h, a, p, p, y, ., , , ]
- 请忽略数组后面的还有的空格,强迫症觉得是个瑕疵。
- Java字符串没有结尾符号’\0’,我就用一个静态变量做了一个备份。
相关题目:有两个排序的数组A1和A2,内存在A1的末尾有足够多的空余空间容纳A2.请实现一个函数,把A2中的所有数字插入到A1中,并且所有的数字都是排序的。
import java.util.Arrays;
public class ReplaceSpaces2 {
private static int[] a = {1, 4, 6, 9, 13, 16, 19, 28, 40, 100};
private static int[] b = {0, 2, 4, 6, 9};
private static void ReplaceBlank(int[] a1, int[] b) {
if (a1 == null || b == null) {
return;
}
int indexOfOriginal = a.length - 1;
int indexOfNew = a1.length - 1;
int indexOfB = b.length - 1;
while (indexOfNew >= 0) {
if (indexOfOriginal >= 0 && indexOfB >= 0) {
if (a1[indexOfOriginal] >= b[indexOfB]) {
a1[indexOfNew] = a1[indexOfOriginal];
indexOfOriginal--;
indexOfNew--;
} else {
a1[indexOfNew] = b[indexOfB];
indexOfB--;
indexOfNew--;
}
} else if (indexOfB >= 0) {
a1[indexOfNew] = b[indexOfB];
indexOfB--;
indexOfNew--;
} else {
a1[indexOfNew] = a1[indexOfOriginal];
indexOfOriginal--;
indexOfNew--;
}
}
System.out.println(Arrays.toString(a1));
}
public static void main(String[] args) {
int[] a1 = Arrays.copyOf(a, a.length + b.length);
ReplaceBlank(a1, b);
}
}
[0, 1, 2, 4, 4, 6, 6, 9, 9, 13, 16, 19, 28, 40, 100]
- 值得注意的是,当有一个数组已经全部插入后,另一个数组可以直接插入。