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 + +)