面试题5:替换空格
题目
该系列文章题目和思路均参考自:《剑指Offer》
解法
思路1:时间复杂度为O(n*n)的解法。从头到尾遍历字符串,遇到空格时将后续的字符串后移2位,然后替换空格为%20。这种方式的时间复杂度为O(n*n)。
思路2:时间复杂度为O(n)的解法。
- 首先遍历一遍数组,计算空格字符的个数,然后扩充字符串的长度为:原始的长度+空格的个数x2。
- 使用两个指针,p1指向原始的字符串的尾,p2指向扩充后的字符串的尾部,从尾至头遍历字符串。
- 如果p1指向的元素不为空,则将它复制给p2。如果为空,则p1指向前一个字符,p2处依次填入%20。
- 然后依次进行,直到p1到达字符串的头部。
代码实现:
public class ReplaceBlank {
public static char[] replaceBlank(char[] str) {
if (str.length == 0)
return null;
int blankCount = 0;
for (int i = 0; i < str.length; i++) {
if (str[i] == ' ') {
blankCount++;
}
}
System.out.println("BlankCount is:" + blankCount + ", char array length is:" + str.length);
int newLength = str.length + blankCount * 2;
char[] result = new char[newLength];
int p1 = str.length - 1;
int p2 = newLength - 1;
while (p1 >= 0 && p2 >= p1) {
if (str[p1] != ' ') {
result[p2--] = str[p1];
} else {
result[p2--] = '0';
result[p2--] = '2';
result[p2--] = '%';
}
p1--;
}
return result;
}
public static void main(String[] args) {
String str = "We are happy!";
char[] array = str.toCharArray();
Utils.printArray(array);
char[] result = replaceBlank(array);
Utils.printArray(result);
}
}
举一反三
在合并两个数组(包括字符串)时,如果从前往后复制每个数字(或字符)需要重复移动元素多次时,可以考虑从后往前复制,这样就可以减少移动的次数,从而提高效率。