JZ02-替换空格
替换空格
https://www.nowcoder.com/practice/0e26e5551f2b489b9f58bc83aa4b6c68?tpId=13&tqId=11155&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&tab=answerKey
/**
* 解法三:从后往前复制
* 分析:由于函数返回为void,说明此题不能另外开辟数组,需要in-place操作。我们知道字符串的遍历无非是从左到右和从右到左两种。
* 1)如果从左到右,会发现如果遇到空格,会将原来的字符覆盖。于是,此方法不行。
* 2)那么就考虑从右向左,遇到空格,就填充“20%“,否则将原字符移动应该呆的位置。
*/
public static String replaceBlank3(StringBuffer input) {
if (input == null || input.length() == 0) {
return null;
}
int spaceNum = 0;
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
spaceNum++;
}
}
int oldLength = input.length();
int oldIndex = oldLength - 1;
int newLength = oldLength + spaceNum * 2;
int newIndex = newLength - 1;
input.setLength(newLength); //重新设置长度
for (; oldIndex >= 0 && oldIndex <= newIndex; oldIndex--) { //oldIndex <= newIndex 最后一个空格前的单词不用重新复制一遍
if (input.charAt(oldIndex) == ' ') {
input.setCharAt(newIndex--, '0');
input.setCharAt(newIndex--, '2');
input.setCharAt(newIndex--, '%');
} else {
input.setCharAt(newIndex--, input.charAt(oldIndex));
}
}
return input.toString();
} 

查看2道真题和解析