1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public String replaceSpaces(String S, int length) {
char[] chars = S.toCharArray(); int spaceCount = 0; for (int i = 0; i < length; i++) { if (chars[i] == ' ') { spaceCount++; } }
for (int i = length - 1, j = length + spaceCount * 2 - 1; i >= 0; i--) { if (S.charAt(i) == ' ') { chars[j--] = '0'; chars[j--] = '2'; chars[j--] = '%'; } else { chars[j--] = chars[i]; } }
return new String(chars, 0, length + spaceCount * 2); } }
|
注意此题含有 S = "ds sdfs afs sdfa dfssf asdf ", length = 27 的测试用例,即尾部有多余空间,所以只能通过扫描得到空格数,而不能通过计算直接得到。
References
面试题 01.03. URL化