0344. Reverse String

0344. Reverse String

一月 04, 2017

344. Reverse String

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”]

思路

题意来讲就是在字符数组中原地前后交换,这里我也采用了异或来做。

但是严格来讲,在这里用异或是错误的。在工程中不允许出现这样的代码。

推荐一篇文章:用异或来交换两个变量是错误的

  • 时间复杂度 O(N)
  • 空间复杂度 O(1)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

impl Solution {
pub fn reverse_string(s: &mut Vec<char>) {

let n = s.len();

if n == 0 {
return;
}

for i in 0..n/2 {
let j = n -1 -i;
s[i] = ((s[i] as u8) ^ (s[j] as u8)) as char;
s[j] = ((s[i] as u8) ^ (s[j] as u8)) as char;
s[i] = ((s[i] as u8) ^ (s[j] as u8)) as char;
}
}
}
  • 执行用时: 28 ms
  • 内存消耗: 5.3 MB

题型与相似题

题型

1.字符串
2.双指针

相似题

代码链接

reverse_string