0344. Reverse String

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)

代码


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

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

您正在使用您的 WordPress.com 账号评论。 登出 /  更改 )

Google photo

您正在使用您的 Google 账号评论。 登出 /  更改 )

Twitter picture

您正在使用您的 Twitter 账号评论。 登出 /  更改 )

Facebook photo

您正在使用您的 Facebook 账号评论。 登出 /  更改 )

Connecting to %s