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;