LeetCode 344 The LeetCode road to reverse string HERODING

Write a function whose role is to reverse the input string. The input string is given in the form of a character array char[].

Don't allocate extra space to another array, you must modify the input array in place and use O(1) extra space to solve this problem.

You can assume that all characters in the array are printable characters in the ASCII code table.

Example 1:

Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]

Example 2:

Input: ["H","a","n","n","a","h"]
Output: ["h","a","n","n","a", "H"]

Problem-solving idea:
This is a fairly simple problem, and there are many ways to solve it. Here I will use two methods. The first is to directly call the reverse function. The code is as follows:

class Solution {
    
    
public:
    void reverseString(vector<char>& s) {
    
    
        std::reverse(s.begin(),s.end());
    }
};

It can be seen that it is very simple and fast, and there is another way to save the vector in the opposite direction. The code is as follows:

class Solution {
    
    
public:
    void reverseString(vector<char>& s) {
    
    
        vector<char> temp(s.size());
        for(int i = s.size() - 1; i >= 0; i --){
    
    
            temp[s.size() - 1 - i] = s[i];
        }
        s = temp;
    }
};

Guess you like

Origin blog.csdn.net/HERODING23/article/details/108958865