Description
Write a method to replace all spaces in a string with %20
. The string is given in a characters array, you can assume it have enough space for replacement and you are given the true L Ength of the string.
You code should also return the new length of the string after replacement.
If you is using Java or python,please use characters array instead of string.
Example
Given "Mr John Smith"
, length = 13
.
The string after replacement should "Mr%20John%20Smith"
is, you need to change the string in-place and return the new length 17
.
Challenge
Do it in-place.
Problem solving: Give a character array, where the space is changed to % 20. because it is in-situ conversion, can not apply for additional space, then can only step back to move backwards. Because the space is converted to "%20", the space used to occupy a unit, now need to occupy three units, as long as the original space behind all the numbers are moved backward two squares. In the process of moving, length also varies. The code is as follows:
1 Public classSolution {2 /*3 * @param string:an array of Char4 * @param length:the True length of the string5 * @return: The true length of the new string6 */7 Public intReplaceblank (Char[] String,intlength) {8 //Write your code here9 for(inti = 0; I <length;) {Ten //If a space is found One if(String[i] = = "){ A for(intj = length-1; J >= I+1; j--){ -STRING[J+2] =String[j]; - } thestring[i++] = '% '; -string[i++] = ' 2 '; -string[i++] = ' 0 '; -Length = length+2; +}Else{ -i++; + } A } at returnlength; - } -}
212. Space replacement "Lintcode by Java"