《剑指offer第二版》面试题5:替换空格(java)
2020-03-04 本文已影响0人
castlet
题目描述
请实现一个函数,把字符串中的每一个空格替换成"%20"。例如,输入"We are happy.",则输出"We%20are%20happy."
解题思路
- 先遍历一遍字符串A,计算出需要替换之后的字符串总长度n。
- 新建总长度为n的char数组B。
- 从后往前遍历A,同时从后往前填充字符串B,如果遍历A中的字符是普通字符,则直接放入B数组内,如果是空格,则向数组B中放入%20三个字符。
代码
String replaceBlank(String str){
if (str == null || str.length() <= 0) {
return str;
}
int finalLength = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
finalLength = finalLength + 3;
} else {
finalLength ++;
}
}
char[] finalChars = new char[finalLength];
int index = finalLength - 1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str.charAt(i) == ' ') {
finalChars[index--] = '0';
finalChars[index--] = '2';
finalChars[index--] = '%';
} else {
finalChars[index--] = str.charAt(i);
}
}
return new String(finalChars);
}