Leetcode344 -- Reverse String (C ++), leetcode344reverse

Source: Internet
Author: User

Leetcode344 -- Reverse String (C ++), leetcode344reverse

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

Example:
Given s = "hello", return "olleh ".

Blog: http://www.cnblogs.com/wdfwolf3 /.

This is a simple string inversion. In C ++, the string type can be processed as an array, so the classic array inversion can be completed. Here we provide two ideas:

1. classic method head-end switching (16 ms)

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. Recursive grouping (44 ms) by recursion method)

The string is divided into two parts: the front and the back, respectively, and then merged. The first half is the front, and the first half is the back. Use the string truncation function string. substr (), which receives two parameters. The first parameter is the position index, that is, the starting position of the truncation. The default parameter is 0, which is the start of the string. The second parameter is the number of characters to be truncated, if omitted, It is truncated to the end of the string.

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, two ideas about swap switching elements are introduced:

1. tmp intermediate variable, the most familiar method.

Tmp = I;

I = tmp;

J = tmp;

2. bitwise OR ^ principle of bit, that is, m ^ m = 0 0 ^ m = m.

M = m & n;

N = m & n; equivalent to n = m & n = m;

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

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.