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