Various implementation algorithms for string reverse order

Source: Internet
Author: User
I have prepared to write a string series of interview questions for a long time. I have already written about a dozen questions, but I found that the article is so long that I have no patience to read it myself, simply split it into several series, and the split will become smaller and more convenient. Second, it is more targeted to facilitate fine-cutting. For example, this article only occupies a small space in the original article, but it is only found that there are many things. Since it is the first article, let's look at the simplest word.

I have prepared to write a string series of interview questions for a long time. I have already written about a dozen questions, but I found that the article is so long that I have no patience to read it myself, simply split it into several series, and the split will become smaller and more convenient. Second, it is more targeted to facilitate fine-cutting. For example, this article only occupies a small space in the original article, but it is only found that there are many things. Since this is the first article, let's look at the simplest string reverse order.

The reverse string is the most frequently used question. This is an entry-level question. I believe 80% of programmers have experienced this question. Given a string s, the character order in s is reversed. for example, s = "abcd" is reversed to s = "dcba ".

General reverse order

This is basically not the case. it is mainly used here to compare it with the back-to-source reverse order. It is very easy to directly allocate an array of long characters such as the original string, and then copy it in reverse order.

Char * Reverse (char * s) {// point q to the last character of the string char * q = s; while (* q ++); q-= 2; // allocate space and store reverse strings. Char * p = new char [sizeof (char) * (q-s + 2)]; char * r = p; // stored in reverse order while (q> = s) * p ++ = * q --; * p = '\ 0'; return r ;}
Reverse order

The English name is in-place reverse. This is the most common test. in-situ reverse order means that extra space allocation is not allowed. There are mainly the following methods with similar ideas: exchange the characters on both sides of the string one by one, for example. Given the string "abcdef", the reverse order is the exchange of character a and f, the exchange of Character B and e, the exchange of character c and d.

Set two pointers, pointing to the header and tail of the string respectively, then exchange the characters referred to by the two pointers, and move the pointer to the middle until the intersection.

Char * Reverse (char * s) {// p points to the string header char * p = s; // q points to the char * q = s at the end of the string; while (* q) + q; q --; // exchange and move the pointer until p and q cross while (q> p) {char t = * p; * p ++ = * q; * q -- = t;} return s ;}

To use recursion, you need to specify the Reverse interval. call method: Reverse (s, 0, strlen (s ));

// Returns the Reverse order of the string s between the left and right in the interval. the recursion method is char * Reverse (char * s, int left, int right) {if (left> = right) return s; char t = s [left]; s [left] = s [right]; s [right] = t; Reverse (s, left + 1, right-1 );}

The non-recursive method also specifies the reverse interval, which is essentially different from Method 1. one uses a pointer and the other uses a subscript.

// Reverse char * Reverse (char * s, int left, int right) {while (left <right) {char t = s [left]; s [left ++] = s [right]; s [right --] = t;} return s ;}
Temporary variables cannot be in reverse order.

Although there is no additional space allocated in the above reverse order, the temporary variables are still used. Strictly speaking, it is also an extra space. if it is more strict, it is not allowed to even the temporary variables, there are two main methods. One is an exclusive or operation, because an exclusive or operation can exchange two variables without the third variable. The other is to use the position of the string terminator '\ 0' as the swap space, there is a limitation that it is only suitable for strings ending with '\ 0'. for languages that do not support this string format, it cannot be used.

Use the position of the string terminator '\ 0' as the swap space:

// Use the position where the string terminator '\ 0' is located as the swap space char * Reverse (char * s) {char * r = s; // point p to the Terminator char * p = s; while (* p! = '\ 0') + + p; // point q to the last character of the string char * q = p-1; // Use p as the swap space to exchange characters one by one while (q> s) {* p = * q; * q -- = * s; * s ++ = * p ;} * p = '\ 0'; // return r ;}

Use an exclusive or operation

// Use an exclusive or operation to Reverse char * Reverse (char * s) {char * r = s; // point p to the last character of the string char * p = s; while (* (p + 1 )! = '\ 0') + + p; // exchange with an exception or operation while (p> s) {* p = * p ^ * s; * s = * p ^ * s; * p = * p -- ^ * s ++;} return r ;}
Sort by words in reverse order

Given a string, the string is in reverse order by words. for example, if "This is a sentence" is specified, the output is "sentence a is This". to simplify the problem, the string does not contain punctuation marks. In two steps:

  1. Obtain "sihT si a ecnetnes" in reverse order of words"
  2. Then, the entire sentence is reversed to get "sentence a is This"

For step 1, the key is how to determine the word. here, space is the word boundary. After finding a word, you can use the method described above to reverse the word. after all the words are in reverse order, think of the entire sentence as a whole (that is, a large word containing spaces) in reverse order. as shown in, the first line is the original character change, the second line is a string in reverse order of words, and the last line is a string in reverse order of the entire sentence.

// Void ReverseWord (char * p, char * q) {while (p <q) {char t = * p; * p ++ = * q; * q -- = t;} // sort the sentence in reverse order of words. char * ReverseSentence (char * s) {// These two pointers are used to determine the boundary char * p = s of a word. // The first character char * q = s pointing to the word; // point to a space or '\ 0' while (* q! = '\ 0') {if (* q = '') {ReverseWord (p, q-1); q ++; // point to the first character of the next word p = q;} else q ++;} ReverseWord (p, q-1); // ReverseWord (s, q-1); // return s in reverse order of the entire sentence ;}
Print in reverse order

Another type of problem is to require reverse output rather than forward storage. This question is very simple. There are several methods below, some of which are less efficient. here we only provide one idea. First obtain the string length, and then traverse it in reverse order.

void ReversePrint(const char* s){    int len = strlen(s) ;    for (int i = len - 1; i >= 0; --i)        cout << s[i];}

If you do not want to evaluate the length of a string, you can first traverse to the end and then traverse back. This requires the string terminator '\ 0 '.

Void ReversePrint (const char * s) {const char * p = s; while (* p) * p ++; -- p; // when while ends, p points to '\ 0'. here, let p point to the last character while (p> = s) {cout <* p; -- p ;}}

For the second method above, you can also use recursion.

void ReversePrint(const char* s){if(*(s + 1) != '\0')ReversePrint(s + 1) ;cout << *s ;}

= The end =

Happy coding!

This article is available at http://www.nowamagic.net/librarys/veda/detail/1057.

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.