Leetcode344--reverse String (c + +)

Source: Internet
Author: User

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

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

Personal blog: http://www.cnblogs.com/wdfwolf3/.

This problem is simple string inverse, in C + + String type can be treated as an array, so the classic array inverse can be done. Here are two ways of thinking:

1.classic method for tail-to-kinsoku Exchange (16MS)

class Solution {public:    string reversestring (string  s) {         int i=0, J=s.size ()-1;          while (i<J)        {            swap (s[i],s[j]);            I+ +;            J--;        }         return s;    }};

2.recursion method Split-treatment recursion (44MS)

The

divides the string into the front and back parts, respectively, and then merges together, and the merge is naturally the second half in front and the first half behind. Use the string intercept function String.substr (), which receives two parameters, the first is the position index, that is, the starting position of the Intercept, the default parameter is 0, is the beginning of the string, the second argument is the number of characters to intercept, if omitted, refers to the end of the string truncated.

class Solution {public:    string reversestring (string  s) {         int length=s.size ();         if (length<2)             return s;         return reversestring (S.substr (length/2)) +reversestring (S.substr (0, length/  2);    }    };

P.S. Finally, there are two ideas about swap elements:

1.TMP Intermediate variable, the most familiar method.

Tmp=i;

i=tmp;

j=tmp;

2.bit the bitwise or ^ principle, namely m^m=0,0^m=m.

m=m&n;

n=m&n; Equivalent to n=m&n&n=m;

m=m&n; m=m&n&m=n;

Leetcode344--reverse String (c + +)

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.