Lintcode: Space substitution
Precautions
If you are using Java or Python, use a character array in your program to represent the string.
Python
Method One: This method does not use a character array, directly using the string array, although can pass, but do not meet the requirements, see Method 2.
class solution: # @param {char[]} string:an array of char # @param {int} length:the True length of the string # @return {int} The true length of new string def Replaceblank(self, string, length): # Write Your code here ifString = =None:return 0 while "' inchString:m = String.index ("') String[m] ='%20 'Length + =2 returnLength
Method Two:
classSolution: #@param{Char[]}string: An array of Char #@param{int} length:thetrueLength of thestring#@return{int} ThetrueLength ofNew stringdef replaceblank (self,string, length): # Write Your code hereif string= = None:return 0 while "' inch string: M =string. Index ("') n = Length length = length +2 whilen > M:string[n+2] =string[n] N-=1 string[M] ='% ' string[m+1] =' 2 ' string[m+2] =' 0 ' returnLength
Java
Public classSolution {/** * @param string:an array of Char * @param length:the True Length of the string * @return: The True Length of new String * / Public int Replaceblank(Char[]string,intLength) {//Write your code here if(Length = =0){return 0; } while(Contains (string)){intM = Index (string);intn = length; Length = length +2; while(n > M) {string[n +2] =string[n]; N-=1; }string[M] ='% ';string[m+1] =' 2 ';string[m+2] =' 0 '; }returnLength }Private StaticBooleancontains(Char[]string){ for(intI=0; i<string. length; i++) {if(string[I] = ="'){return true; } }return false; }Private Static int Index(Char[]string){ for(intI=0; i<string. length; i++) {if(string[I] = ="'){returnI } }return 0; }}
Lintcode: Space substitution