Data Structure string of typical programming questions

Source: Internet
Author: User

Data Structure string of typical programming questions

A string is a sequence of several characters. Because strings are frequently used for programming, many languages have made special rules on strings for optimization. The following describes the features of strings in C/C ++ and C # respectively.

In C/C ++, each string ends with the character '\ 0', so that we can easily find the end and end of the string. However, due to this feature, each string has an additional character overhead, which may cause the string to be out of bounds. For example, the following code:

Char STR [10];

Strcpy (STR, "0123456789 ");

We declare an array of 10 characters first, and then copy the string "0123456789" to the array. "0123456789" this string looks to have only 10 characters, but it actually has a '\ 0' character at the end, so its actual length is 11 bytes. To copy the string correctly, an array of at least 11 bytes is required.

To save memory, C/C ++ places the constant string in a separate memory area. When several pointers are assigned to the same constant string, they actually point to the same memory address. However, the array is initialized with constant memory, but the situation is different. Next we will learn this knowledge point through an interview question. Run the following code. What is the result?

Int _ tmain (INT argc, _ tchar * argv [])

{

Char str1 [] = "Hello World ";

Char str2 [] = "Hello World ";

 

Char * str3 = "Hello World ";

Char * str4 = "Hello World ";

 

If (str1 = str2)

Printf ("str1 and str2 are same. \ n ");

Else

Printf ("str1 and str2 are notsame. \ n ");

 

If (str3 = str4)

Printf ("str3 and str4 aresame. \ n ");

Else

Printf ("str3 and str4 are notsame. \ n ");

 

Return 0;

}

Str1 and str2 are two string arrays. We will allocate two 12-byte spaces for them, and copy the "Hello World" contents to the array respectively. These are two arrays with different initial addresses, so the values of str1 and str2 are also different, so the first line of output is "str1 and str2 are not same ".

Str3 and str4 are two pointers. Instead of allocating memory for them to store string content, we only need to point them to the address in the memory of "helloworld. Because "Hello world" is a constant string and has only one copy in the memory, str3 and str4 point to the same address. Therefore, the result of comparing str3 and str4 is the same, and the second line of output is "str3 and str4 are same ".

In C #, the string encapsulation type system. String has a very special property: the content in the string cannot be changed. Once you try to change the string content, a new instance will be generated. See the following C # code:

String STR = "hello ";

Str. toupper ();

Str. insert (0, "world ");

Although we have performed toupper and insert operations on STR, the results of the operations are to generate a new string instance and return it in the return value. The content of STR itself will not change, therefore, the final str value is still "hello ". It can be seen that if you try to change the content of the string, the changed value can only be obtained through the return value. If you use string for multiple consecutive modifications, each change will generate a temporary object. This overhead will affect efficiency. Therefore, C # defines a new string-related type stringbuilder, which can accommodate the modified results. Therefore, it is better to use stringbuilder to modify the string content multiple times in a row.

Similar to modifying the string content, if we try to assign a constant string to a string instance, instead of changing the string content to a value string, We will generate a new string instance. See the following code:

Class Program

{

Internal static void valueorreference (typetype)

{

String result = "the type" + type. Name;

 

If (type. isvaluetype)

Console. writeline (result + "is avalue type .");

Else

Console. writeline (result + "is a reference type .");

}

 

Internal static void modifystring (stringtext)

{

TEXT = "world ";

}

 

Static void main (string [] ARGs)

{

String text = "hello ";

 

Valueorreference (text. GetType ());

Modifystring (text );

 

Console. writeline (text );

}

}

In the above Code, we first determine whether the string is a value type or a reference type. The Type string is defined as public sealed class string {...}. Since it is a class, string is a reference type. Next, assign a new string to text in the modifystring method. We must remember that the text content cannot be modified. In this case, a new string with the content "world" will be generated, and text will be directed to this new instance. Since the text parameter does not contain ref or out, after the modifystring method is used, the text still points to the original string, so the output is still "hello ". To achieve the effect of converting text into "world" after a function is implemented, we must mark the parameter text with ref or out.

Interview question 4: replacing Spaces

Question: implement a function and replace each space in the string with "% 20 ". For example, if "We are happy." Is input, "We % 20are % 20happy." Is output .".

In network programming, if URL parameters contain special characters, such as spaces and '#', the server may fail to obtain the correct parameter value. We need to convert these special characters into characters that can be recognized by the server. The conversion rule is followed by two hexadecimal representations of the ASCII code after '%. For example, if the ASCII code of a space is 32, that is, the hexadecimal 0x20, the space is replaced with "% 20 ". For example, if the '#' ASCII code is 35, that is, the hexadecimal 0x23, it is replaced with "% 23" in the URL ".

When we see this question, we should first think of a space character, which is replaced with three characters: '%', '2', and '0', so the string will become longer. If the original string is replaced, the memory after the string may be overwritten. If you create a new string and replace it with the new string, you can allocate enough memory. Because there are two different solutions, we should ask the interviewer clearly so that he can clearly tell us his needs. Assume that the interviewer asked us to replace the original string and ensure that there is enough free memory behind the input string.

The time complexity is O (n2 ).

Now we want to consider how to perform the replacement operation. The most intuitive way is to scan strings from start to end and replace each time a space character is encountered. Because we replace one character with three characters, we must move all the characters after the space two bytes later. Otherwise, two characters will be overwritten.

For example, we replace each space in "We are happy." with "% 20" from start to end ". For the sake of image, we can use a table to represent strings. Each grid in the table represents a character (as shown in 2.3 ().

 

Figure 2.3 process of replacing spaces in strings with '% 20'

Note: (a) string "weare happy .". (B) Replace the first space in the string with '% 20 '. The gray background indicates the characters to be moved. (C) Replace the second space in the string with '% 20 '. A light gray background indicates the characters that need to be moved once, and a dark gray background indicates the characters that need to be moved twice.

We replace the first space. The string is changed to the content in Figure 2.3 (B). The gray background lattice in the table indicates the area to be moved. Then we replace the second space, and the content after replacement is 2.3 (c. At the same time, we noticed that the "happy" section marked with a dark gray background was moved twice.

Assume that the length of the string is N. For each space character, it is necessary to move the following O (n) characters. Therefore, the total time efficiency for strings containing O (n) space characters is O (n2 ).

When we explain this idea to the interviewer, he will not be satisfied with it. He will help us find a faster way. In the previous analysis, we found that many characters in the array have been moved many times. can we reduce the number of moves? The answer is yes. In another way, we can replace the former with the latter.

The time complexity is O (n), and it is enough to deal with offer.

We can traverse the string first, so that we can calculate the total number of spaces in the string and calculate the total length of the string after replacement. Each replacement of a space increases by 2. Therefore, the length of the string after replacement is equal to the original length plus 2 multiplied by the number of spaces. We still use the previous string "we are happy. "For example," We arehappy. "The length of this string is 14 (including the ending sign '\ 0'), which contains two spaces. Therefore, the length of the string after replacement is 18.

We Start copying and replacing strings. First, prepare two pointers, P1 and P2. P1 points to the end of the original string, while P2 points to the end of the replaced string (2.4 (). Next we move the pointer P1 forward and copy the characters it points to the position pointed to by P2 one by one until the first space is reached. In this case, the string contains 2.4 (B), and the area of the gray background is the area where the characters are copied (moved. When the first space is reached, move P1 forward to the first space and insert the string "% 20" before P2 ". Since the length of "% 20" is 3, P2 must also be moved forward, as shown in 3 lattice 2.4 (c.

We then copy it forward until we encounter the second space (2.4 (d ). Like the previous one, we move P1 to the first frame and insert p2 to the third frame "% 20" (2.4 (e ). At this time, P1 and P2 point to the same position, indicating that all spaces have been replaced.

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

 

Figure 2.4 process of replacing the space in the string with "% 20" from the back

Note: The area with shadow in the figure indicates the character to be moved. (A) point the first pointer to the end of the string and the second pointer to the end of the replaced string. (B) copy the content of the string in sequence until the first pointer encounters the first space. (C) Replace the first space with '% 20', move the first Pointer Forward to the first space, and move the second Pointer Forward to the Third Space. (D) Copy the characters in the string forward until spaces are met. (E) Replace the second to last space in the string, move the first Pointer Forward to the first space, and move the second Pointer Forward to the Third Space.

During the interview, we can draw one or two ideas to explain ourselves like the previous analysis. This will help us clarify our ideas, it can also make our communication with the interviewer more efficient. After the interviewer confirms our ideas, he can start to write code. The following is the reference code:

/* Length is the total size of the string character array */

Voidreplaceblank (char string [], int length)

{

If (string = NULL & length <= 0)

 

 

Return;

 

/* Originallength is the actual length of the string */

Int originallength = 0;

Int numberofblank = 0;

Int I = 0;

While (string [I]! = '\ 0 ')

{

++ Originallength;

 

If (string [I] = '')

++ Numberofblank;

 

++ I;

}

 

/* Newlength is the length after replacing the space with '% 20 */

Int newlength = originallength + numberofblank * 2;

If (newlength> length)

Return;

 

Int indexoforiginal = originallength;

Int indexofnew = newlength;

While (indexoforiginal> = 0 & indexofnew> indexoforiginal)

{

If (string [indexoforiginal] = '')

{

String [indexofnew --] = '0 ';

String [indexofnew --] = '2 ';

String [indexofnew --] = '% ';

}

Else

{

String [indexofnew --] = string [indexoforiginal];

}

 

-- Indexoforiginal;

}

}

Source code:

For the complete source code of this question, see the 04_replaceblank project.

Test cases:

The input string contains spaces (spaces are at the beginning of the string, spaces are at the end of the string, spaces are in the middle of the string, and strings contain consecutive spaces ).

The input string contains no spaces.

Special input test (a string is a null pointer, a string is a Null String, a string contains only one space character, and a string contains only multiple consecutive spaces ).

Exam point:

Measure the test taker's knowledge about string programming.

Measure the test taker's knowledge about time efficiency. We need to be able to clearly analyze the time efficiency of the two different methods.

Measure the test taker's knowledge about memory coverage. After the analysis shows that the string will become longer, we can be aware of potential problems and actively communicate with the interviewer to find a solution to the problem.

Examine the thinking ability. After the thought of replacing from the past to the next is rejected by the interviewer, we can quickly think of the method of replacing from the back to the next. This is the key to solving this problem.

Related questions:

There are two sorted arrays A1 and A2, and there is enough free space at the end of A1. Implement a function to insert all numbers in A2 into A1. all numbers are sorted.

As in the previous example, many people first think of copying numbers from start to end in A1, but this will result in multiple copies of a number. A better way is to compare the numbers in A1 and A2 from the end to the end, and copy the large numbers to the proper location of A1.

Trigger:

When merging two arrays (including strings), if you need to repeatedly move a number (or character) multiple times before and after copying each number (or character), you can consider copying from the back to the back, this can reduce the number of moves and improve efficiency.

 

This article is from the book "offoffoffer-famous enterprise interviewer excellent typical programming questions"

Book details: http://blog.csdn.net/broadview2006/article/details/7043805

 

 

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.