题目:请实现一个函数,把字符串中的每个空格替换成”%20”,例如,输入”We are happy.”,则输出”We%20are%20happy.”。
思路:通过两次遍历进行处理,第一次遍历统计字符串的所有空格数量,计算替换之后字符串的长度,并且为新字符串分配空间,第二次是从尾部遍历字符串,并且从尾部开始把一个一个字符复制到新分配的空间中去,遇到空格就替换,这样就避免了数组的重复平移操作。
代码:
public class ReplaceBlank { public static void main(String[] args) { char[] str = {'W', 'e', ' ', 'a', 'r', 'e',' ','h','a','p','p','y','.'}; char[] newStr = replaceBlank(str); System.out.println(newStr); } public static char[] replaceBlank(char[] str) { int newLength = 0; // 第一次从头到尾遍历统计替换之后的长度 for (int i = 0; i < str.length; i++) { if (str[i] == ' ') { newLength += 3; } else { newLength += 1; } } char[] newStr = new char[newLength]; int newIndex = newLength -1; // 第一次从尾到头的遍历进行替换 for (int i = str.length - 1; i >= 0; i--) { if (str[i] == ' ') { newStr[newIndex] = '0'; newStr[newIndex-1] = '2'; newStr[newIndex-2] = '%'; newIndex = newIndex - 3; } else { newStr[newIndex] = str[i]; newIndex--; } } return newStr; } }启发:合并两个数组(包括字符串)时,如果从前往后复制需要重复移动多次,那么可以考虑从后往前复制,这样可以减少移动的次数,提高效率。