class Solution {
public:
void reverseString(vector<char>& s) {
}
};
344. 反转字符串
编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 s
的形式给出。
不要给另外的数组分配额外的空间,你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。
示例 1:
输入:s = ["h","e","l","l","o"] 输出:["o","l","l","e","h"]
示例 2:
输入:s = ["H","a","n","n","a","h"] 输出:["h","a","n","n","a","H"]
提示:
1 <= s.length <= 105
s[i]
都是 ASCII 码表中的可打印字符原站题解
javascript 解法, 执行用时: 100 ms, 内存消耗: 47.9 MB, 提交时间: 2023-08-07 09:43:33
/** * @param {character[]} s * @return {void} Do not return anything, modify s in-place instead. */ var reverseString = function(s) { const n = s.length; for (let left = 0, right = n - 1; left < right; ++left, --right) { [s[left], s[right]] = [s[right], s[left]]; } };
java 解法, 执行用时: 0 ms, 内存消耗: 49.4 MB, 提交时间: 2023-08-07 09:33:42
class Solution { public void reverseString(char[] s) { int n = s.length; for (int left = 0, right = n - 1; left < right; ++left, --right) { char tmp = s[left]; s[left] = s[right]; s[right] = tmp; } } }
cpp 解法, 执行用时: 20 ms, 内存消耗: 22.6 MB, 提交时间: 2023-08-07 09:30:02
class Solution { public: void reverseString(vector<char>& s) { int n = s.size(); for (int left = 0, right = n - 1; left < right; ++left, --right) { swap(s[left], s[right]); } } };
golang 解法, 执行用时: 28 ms, 内存消耗: 6.3 MB, 提交时间: 2023-08-07 09:28:14
func reverseString(s []byte) { for left, right := 0, len(s)-1; left < right; left++ { s[left], s[right] = s[right], s[left] right-- } }
golang 解法, 执行用时: 32 ms, 内存消耗: 6.5 MB, 提交时间: 2021-07-15 09:32:23
func reverseString(s []byte) { left, right := 0, len(s) - 1 for left < right { s[left], s[right] = s[right], s[left] left++ right-- } }
python3 解法, 执行用时: 96 ms, 内存消耗: N/A, 提交时间: 2018-08-25 11:19:00
class Solution: def reverseString(self, s): """ :type s: str :rtype: str """ l = [c for c in s] l.reverse() return ''.join(l)