Topic:
Space Substitution
Design a method that replaces all the spaces in a string with a %20 . You can assume that the string has enough space to add new characters, and you get the "real" character length.
Sample Example
For strings "Mr John Smith" , the length is13
The result after replacing a space is"Mr%20John%20Smith"
Note
If you are using Java or Python, use a character array in your program to represent the string.
Solving:
A problem that indicates the lowest pass rate ....
Link it with a Java string, then ToCharArray, then go out and pick up the same as before, the original%20 represents a space .... Reference program, directly in the original Char array operation, the first new string array of length, and then insert the% 20, so that the solution, for the post-insertion solution encountered, the topic will give such a hint: assuming that the string has enough space to add new characters , according to the question to find the answer , look for ideas.
Java Program:
Public classSolution {/** * @paramString:an Array of Char *@paramlength:the True Length of the string *@return: The true length of new string*/ Public intReplaceblank (Char[] String,intlength) { //Write Your code here intReallen =length; for(inti = 0;i<length;i++){ if(String[i] = = ") Reallen+ = 2; } intindex =Reallen; for(inti = length-1;i>= 0; i-- ){ if(String[i] = = ") {string[--index] = ' 0 '; string[--index] = ' 2 '; string[--index] = '% '; }Else{string[--index] =String[i]; } } returnReallen; }}View Code
Total time: 1137 Ms
Python program:
classSolution:#@param {char[]} string:an array of char #@param {int} length:the True length of the string #@return {int} The true length of new string defReplaceblank (self, string, length):#Write Your code here ifstring==None:returnNone Reallen=length forSiinchstring:ifsi==' ': Reallen+ = 2Index=Reallen forIinchRange (length-1,-1,-1): ifString[i] = =' ': Index-= 1string[Index]='0'Index-= 1string[Index]='2'Index-= 1string[Index]='%' Else: Index-= 1string[Index]=String[i]returnReallenView Code
Total time: 393 Ms
Lintcode Easy title: Space Replacement Space replacement