[Algorithm path] string reverse output

Source: Internet
Author: User

I. preface the reverse output of the string is a classic interview question, which is not difficult to implement. However, what the interviewer wants to see is whether the interviewer can use the shortest code to more efficiently implement the reverse function of the string. In other words, there are three points: time complexity, space complexity, and code readability. No matter what Code does, these three points are good code. Next, I will introduce two methods to implement reverse string sorting. For details, see the following. Ii. method 1 for realizing the reverse output of strings: exclusive or method this method is a relatively simplified method that uses binary directly for computation, you will understand the code.

Char * reverse_str (char * str) {size_t len = 0; unsigned int I, j; len = strlen (str); for (I = 0, j = len-1; I
 
  
Method 2: The half-right method is my own name. It may not be too accurate. The principle is to define an intermediate variable to switch from the beginning to the end until it reaches a character in the middle of the string.
  
Char * reverse_str (char * str) {size_t len = 0; unsigned int I; char temp; len = strlen (str); for (I = 0; I
   
    
Or define two variables, I, j.
    
Char * reverse_str (char * str) {size_t len = 0; unsigned int I, j; char temp; len = strlen (str); for (I = 0, j = len-1; I
     
      
Conclusion: The time complexity and space complexity of the two methods are very small, regardless of the difference or method and the half-right method. So far, I think the two methods are more feasible. If you have any better methods, please share them with us. There are also many other methods on the Internet, such as opening up a new space and so on. I don't want to introduce them here. I think it is best not to apply for new memory in the code, A variable may think there is nothing but it accumulates much. Especially on embedded devices, the memory is very valuable, so we do not recommend this.
     

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.