Title: Replace all spaces in a string (char array) with "%20". This assumes that there is enough free space in the array so you do not need to extend the array
The idea of solving a problem is to determine how many spaces are in the array first so you can know how long the new array is and then iterate through the array, moving the last character in the string from the last start to the new last position, and then the penultimate one. Once the space is encountered, it will be ' 0 ', ' 2 ', '% ' three characters Don't insert a new location and so on
The code is as follows
Public voidMySolution (Char[] str) { intLast =Findlastchar (str); if(last==0) {str=NULL; return; } intNumofspace =countspace (str, last); intNewlastchar =Findnewlastchar (str, numofspace); intA = last, B =Newlastchar; while(a>=0){ if(str[a]!= ") {str[b--] =Str[a]; }Else{str[b--] = ' 0 '; Str[b--] = ' 2 '; Str[b--] = '% '; } A--; } } Private intFindlastchar (Char[] a) { intLast = 0; for(intI=a.length-1; i>=0; i--){ if(a[i]== ")Continue; Last=i; Break; } returnLast ; } Private intCountspace (Char[] A,intoldlast) { if(oldlast==0)return0; intCount = 0; for(inti=0; i<oldlast; i++)if(a[i]== ") count++; returncount; } Private intFindnewlastchar (Char[] A,intSpacecount) { intLast =Findlastchar (a); if(spacecount==0)returnLast ; Else returnlast+2*Spacecount; }
This method assumes that the first character is not a space if there are several spaces in front of the string, the spaces are also changed to "%20"
The Findlastchar run time in this method is O (n) countspace and Findnewlastchar run time are O (1) While the run time of the loop is O (n) so the total run time is O (n)
This method does not require additional space, so the time complexity is O (1)
Interview question 4 replace all spaces in a char array with%20