Interview question 4 replace all spaces in a char array with%20

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.