Reverse String


1、タイトルの要求
Write a function that reverses a string. The input string is given as an array of characters char[].
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
You may assume all the characters consist of printable ascii characters.
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”]
反転文字列の関数を作成します.入力文字列はchar[]文字配列で与えられます.
別の配列に余分なスペースを割り当てるのではなく、O(1)余分なメモリを使用して入力配列を変更することで、この目的を達成する必要があります.
すべての文字に印刷可能なascii文字が含まれていると仮定できます.
2、テーマの考え方
この問題に対して,O(1)の空間内で文字列の反転を実現する.
テーマは簡単で,swap関数を直接利用して前後要素の交換を実現すればよい.for(文字列長が0の場合判断しておく必要がある)を利用してもよいし、while(文字列長を判断しなくてもよい)を直接使用してもよい
3,コード実装
1,for
static const auto s = []() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    return nullptr;
}();


class Solution {
public:
    void reverseString(vector<char>& s) {
        int n = s.size();
        if(n <=1 )
            return;
        
        for(int i = 0;i<n/2;i++)
            swap(s[i], s[n-i-1]);
        return;
    }
};

2,while
class Solution {
public:
    void reverseString(vector<char>& s) {
        int n = s.size();
        int i = 0, j = n-1;
        while(i<j)
            swap(s[i++],s[j--]);
        return;
    }
};