The sword refers to the offer face Question 4 (Java edition), replaces the space

Source: Internet
Author: User

Title: Please implement a function that replaces each space in the string with the "%20". For example, enter "We are happy", then output "We%20are%20happy".

Reason: In network programming, if the URL parameter contains special characters, such as: space, "#", etc., may cause the server side can not get the correct parameter values. We need to convert these special symbols into characters that are recognized by the server. The conversion rule is a two-bit hexadecimal table with ASCII code after "%". For example: The ASCII of a space is 32, that is, hexadecimal 0x20, so the space is replaced with "%20".

time Complexity O (N2) Not enough to get an offer

Now let's consider how to do the substitution operation. The most intuitive approach is to scan the string from start to finish, and replace each time you encounter a space character. Since it is the substitution of 1 characters for 3 characters, we must move all the characters behind the space by two bytes, or two characters will be overwritten.

For example, we replace each space in "We are happy" with "%20" from beginning to end. For the duration of the image, we can use a table to represent the string, and each lattice in the table represents one character. As shown in the following illustration:


We replaced the first space, this string programming the content in Figure B, the gray background in the table indicates the character that needs to be moved. We then replace the second space and replace it with the following as shown in Figure C. At the same time, we noticed that the "happy" part was moved two times with the dark gray Beijing label.

Suppose the length of the character is N. For each space character, you need to move the back O (n) characters, so the total time efficiency for an O (n) space string is O (n2).

When we put this kind of thinking to the interviewer, he won't be satisfied, he will let us find a quicker way. In the previous analysis, we found that many of the characters in the array were moved many times and could reduce the number of moves. Let's change our mind and replace the previous one backwards from the back forward.

Consider the time complexity of O (n) solution, to deal with the offer depends on it

We first iterate through the string so that we can count the summary of the string's hollowness and calculate the total length of the string after the substitution. With each space replaced, the length increased by 2, so the length of the replacement string is equal to the original length plus 2 times the number of spaces, we still take the previous string "We are happy" for example, "We are happy" the length of this string is 14, with two spaces inside, So the length of the string after the replacement is 18

We start copying and replacing from the back of the string.   First prepare two pointers, P1 and P2. P1 points to the end of the original string, and P2 points to the end of the replaced string. Next we move the pointer P1, one by one, to copy the character it points to the P2 point, until the first space is encountered. The string is now included as shown in Figure B, and the shaded area is the area where the character copy is made. After you hit the first space, move the P1 forward one, and insert the string "%20" before P2, as the length of "%20" is 3, and the P2 is moved forward 3 squares as shown in the figure.

We then copied forward until we encountered the second space (d). Like the last time, we move the P1 1 squares forward and move the P2 forward 3 squares to the "%20" (Figure E), at which point p1,p2 points to the same location, indicating that all the spaces have been replaced.

From the above analysis we can see that all the characters are copied only once, so the time efficiency of this algorithm is O (n), faster than the first train of thought.



Implemented as follows:

Package My_java;
		public class test{//The number of spaces included in the calculation string public static int Getblanknum (String teststring) {int count = 0;
			for (int i = 0;i<teststring.length (); i++) {String tempstring = string.valueof (Teststring.charat (i));
			if (Tempstring.equals ("")) {count++;
	} return count;
		}//Print char[] array public static void PrintArray (char[] testarray) {for (char I:testarray) {System.out.print (i);
	} System.out.println (); ///Convert string spaces to 20% public static void Replaceallblank (String teststring) {if (teststring = = NULL | | teststring.length () &
		lt;= 0) {return;
		}//character array initial length int = length = Teststring.length ();
		Character array added length after int newlength = teststring.length () + getblanknum (teststring) *2;
		char[] Temparray = new Char[newlength];
		System.arraycopy (Teststring.tochararray (), 0, Temparray, 0, Teststring.tochararray (). length);
		int indexoforiginal = length-1;
		int indexofnew = newLength-1;
		System.out.println ("String with no space replaced:"); PrintArray (Teststring.tochararrAy ()); while (indexoforiginal >=0 && indexoforiginal!= indexofnew) {if (temparray[indexoforiginal]== ') {tempAr
				ray[indexofnew--]= ' 0 ';
				temparray[indexofnew--]= ' 2 ';
			temparray[indexofnew--]= '% ';
			}else{temparray[indexofnew--]= temparray[indexoforiginal];
		} indexoforiginal--;
		System.out.println ("String after space replaced:");
	PrintArray (Temparray);
		public static void Main (string[] args) {String str = "We are happy";
	Replaceallblank (str);
 }
}



Related Article

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.