Leetcode 344.Reverse String

Source: Internet
Author: User

Test instructions

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "Hello", Return "Olleh".

Implements the reversal of a string.

At first, I was the direct string fan, and then I gave the fan a value, and I found that the output was an empty string. The solution is not to be baffled. Then use char fan[length], and then assign the value to get the result of the reversal. However, less consideration is given to the incorrect output when the s= "" is turned on. The error is then corrected, the fan is initialized to S, and then reversed with a for loop to get the correct answer. The code is as follows:

class Solution {public:    string reversestring (string  s) {         int length = s.length ();         string fan = s;          for (int0; i < length; i++)         = s[length-1-i];         return fan;    }};

The efficiency diagram for the code is as follows:

Sure enough, the method is not very efficient.

After thinking that the reverse function in the string library might be better and more efficient, the code is written as follows:

class Solution {public:    string reversestring (string  s) {        Reverse (S.begin (), S.end ());         return s;    }};

The code is really short, but the efficiency is not improved, or as with the For loop, the reverse function may also be written in a loop.

Then think of the loop that can be cut in half short:

class Solution {public:    string reversestring (string  s) {         int length = s.length ();          for (int0; i < length/2 ; i++)        swap (s[i],s[length-1- i]);         return s;    }};

However, the effect is not ideal, or the same as the original.

Looking at discuss, I found that most of the answers were the same.

Summarize:

This problem consolidates the knowledge of string, which was previously thought to directly modify data of type string.

Leetcode 344.Reverse String

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.