Try   HackMD

【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.

寫一個函式能夠反轉一個字串。輸入字串會使用字元陣列char[]

不要配置任何額外的空間在其他陣列上,你應該在額外記憶體O(1)的原地演算法條件下,改變輸入字串完成它。

你可以假設所有字串都包含在可顯示字元中。

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

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++