-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
#### 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"] | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
[package] | ||
name = "reverse_string" | ||
version = "0.1.0" | ||
authors = ["Jimmy Xiang <[email protected]>"] | ||
|
||
[dependencies] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
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; | ||
} | ||
} | ||
|
||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn it_works() { | ||
let mut test = vec!['x','x','g']; | ||
reverse_string(&mut test); | ||
assert_eq!(vec!['g','x','x'], test); | ||
} | ||
} |