# 【LeetCode】 344. Reverse String ## Description > 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](https://en.wikipedia.org/wiki/ASCII#Printable_characters). > 寫一個函式能夠反轉一個字串。輸入字串會使用字元陣列`char[]`。 > 不要配置任何額外的空間在其他陣列上,你應該在額外記憶體O(1)的原地演算法條件下,改變輸入字串完成它。 > 你可以假設所有字串都包含在[可顯示字元](https://zh.wikipedia.org/wiki/ASCII#%E5%8F%AF%E6%98%BE%E7%A4%BA%E5%AD%97%E7%AC%A6)中。 ## Example: ``` 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"] ``` ## Solution * 這題雖然題目說給予的是`char[]`,但實際上是`vector<char>`,應該是有改過題目的型別但忘了改敘述。 * 也因為這樣,執行時間會輸給很多人,推測是因為以前不用使用`vector`速度較快。 * 反轉字串,將第一個和最後一個交換、第二個和倒數第二交換......第`i`個和第`n - i`個交換即可。 ### Code ```C++=1 class Solution { public: void reverseString(vector<char>& s) { char temp; int S = s.size(); for(int i = 0; i < S / 2; i++) { temp = s[i]; s[i] = s[S - 1 - i]; s[S - 1 - i] = temp; } } }; ``` ###### tags: `LeetCode` `C++`