跳到主要内容

344.反转字符串

链接:344.反转字符串
难度:Easy
标签:双指针、字符串
简介:编写一个函数,其作用是将输入的字符串反转过来。输入字符串以字符数组 char[] 的形式给出。

题解 1 - cpp

  • 编辑时间:2023-08-07
  • 执行用时:20ms
  • 内存消耗:22.15MB
  • 编程语言:cpp
  • 解法介绍:遍历。
class Solution {
public:
void reverseString(vector<char>& s) {
int l = 0, r = s.size() - 1;
while (l < r) swap(s[l++], s[r--]);
}
};

题解 2 - rust

  • 编辑时间:2023-08-07
  • 执行用时:16ms
  • 内存消耗:5.26MB
  • 编程语言:rust
  • 解法介绍:同上。
impl Solution {
pub fn reverse_string(s: &mut Vec<char>) {
let mut l = 0;
let mut r = s.len() - 1;
while l < r {
let (cl, cr) = (s[l], s[r]);
s[l] = cr;
s[r] = cl;
l += 1;
r -= 1;
}
}
}

题解 3 - typescript

  • 编辑时间:2020-10-08
  • 执行用时:128ms
  • 内存消耗:45.6MB
  • 编程语言:typescript
  • 解法介绍:调用原生方法。
function reverseString(s: string[]): void {
s.reverse();
}

题解 4 - typescript

  • 编辑时间:2020-10-08
  • 执行用时:140ms
  • 内存消耗:46.1MB
  • 编程语言:typescript
  • 解法介绍:双指针替换。
function reverseString(s: string[]): void {
for (let l = 0, r = s.length - 1; l < r; l++, r--) {
[s[l], s[r]] = [s[r], s[l]];
}
}

题解 5 - python

  • 编辑时间:2023-08-07
  • 执行用时:60ms
  • 内存消耗:20.86MB
  • 编程语言:python
  • 解法介绍:同上。
def swap(node: Optional[ListNode], cnt: int, max_cnt: int) -> (Optional[ListNode], Optional[ListNode]):
if not node:
return (None, None)
elif cnt == max_cnt:
node.next = swap(node.next, 1, max_cnt)[0]
return (node, node)
elif not node.next:
return (node, node)
else:
res = swap(node.next, cnt + 1, max_cnt)
node.next = res[1].next
res[1].next = node
return res
class Solution:
def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
return swap(head, 1, 2)[0]

题解 6 - typescript

  • 编辑时间:2020-10-08
  • 执行用时:128ms
  • 内存消耗:45.6MB
  • 编程语言:typescript
  • 解法介绍:调用原生方法。
function reverseString(s: string[]): void {
s.reverse();
}

题解 7 - typescript

  • 编辑时间:2020-10-08
  • 执行用时:140ms
  • 内存消耗:46.1MB
  • 编程语言:typescript
  • 解法介绍:双指针替换。
function reverseString(s: string[]): void {
for (let l = 0, r = s.length - 1; l < r; l++, r--) {
[s[l], s[r]] = [s[r], s[l]];
}
}

题解 8 - javascript

  • 编辑时间:2020-04-07
  • 执行用时:136ms
  • 内存消耗:46.7MB
  • 编程语言:javascript
  • 解法介绍:直接翻转即可。
/**
* @param {character[]} s
* @return {void} Do not return anything, modify s in-place instead.
*/
var reverseString = function (s) {
s.reverse();
};