Space Replacement
Write a method to replace all spaces in a string with %20
. The string is given in a characters array, you can assume it has enough space for replacement and you are given the true length of the string.
You code should also return the new length of the string after replacement.
Notice
If you are using Java or Python,please use characters array instead of string.
Example
Given "Mr John Smith"
, length = 13
.
The string after replacement should be "Mr%20John%20Smith"
, you need to change the string in-place and return the new length 17
.
分析:
先过一遍,找出string里的空格个数,这样就可以确定新string的总长度,我们可以从length -1 那个地方倒着插入字符。
1 public class Solution { 2 /** 3 * @param string: An array of Char 4 * @param length: The true length of the string 5 * @return: The true length of new string 6 */ 7 public int replaceBlank(char[] str, int length) { 8 if (str == null || str.length == 0) return 0; 9 10 int count = 0; 11 for (int i = 0; i < str.length; i++) { 12 if (str[i] == ' ') count++; 13 } 14 15 int index = length + 2 * count - 1; 16 17 for (int i = length -1; i >= 0; i--) { 18 if (str[i] == ' ') { 19 str[index--] = '0'; 20 str[index--] = '2'; 21 str[index--] = '%'; 22 } else { 23 str[index--] = str[i]; 24 } 25 } 26 27 28 return length + 2 * count; 29 30 } 31 }