Skip to content

Commit 78aada2

Browse files
authored
Merge pull request #19 from jtr109/reverse-words-in-a-string-iii
Reverse words in a string iii
2 parents e2206a6 + 4adfc6f commit 78aada2

File tree

5 files changed

+68
-0
lines changed

5 files changed

+68
-0
lines changed

Cargo.lock

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,4 +10,5 @@ members = [
1010
"merge_sorted_array",
1111
"intersection_of_two_arrays",
1212
"longest_palindromic_substring",
13+
"reverse_words_in_a_string_iii",
1314
]

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Resolving problems of LeetCode in RustLang.
1616
* [215. Kth Largest Element in an Array](./kth_largest/src/lib.rs)
1717
* [232. Implement Queue using Stacks](./implement_queue_using_stacks/src/lib.rs)
1818
* [349. Intersection of Two Arrays](./intersection_of_two_arrays/src/lib.rs)
19+
* [557. Reverse Words in a String III](./reverse_words_in_a_string_iii/src/lib.rs)
1920

2021
## Document
2122

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
[package]
2+
name = "reverse_words_in_a_string_iii"
3+
version = "0.1.0"
4+
authors = ["Ryan Li <conbas2019@gmail.com>"]
5+
edition = "2018"
6+
7+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
8+
9+
[dependencies]
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*!
2+
* # 557. Reverse Words in a String III
3+
*
4+
* [Problem link](https://leetcode.com/problems/reverse-words-in-a-string-iii/)
5+
*/
6+
7+
#![allow(dead_code)]
8+
9+
struct Solution {}
10+
11+
// ----------------------------------------------------------------------------
12+
13+
impl Solution {
14+
pub fn reverse_words(s: String) -> String {
15+
let mut i = 0;
16+
let chars = s.chars().collect::<Vec<char>>();
17+
let mut reversed = vec![];
18+
while i < s.len() {
19+
if chars[i] == ' ' {
20+
reversed.push(chars[i]);
21+
i += 1;
22+
continue;
23+
}
24+
let mut j = i;
25+
while j < s.len() && chars[j] != ' ' {
26+
j += 1;
27+
}
28+
let mut k = j - 1;
29+
loop {
30+
// push the char into the reversed vector until reach the index `i`
31+
reversed.push(chars[k]);
32+
if k == i {
33+
break;
34+
}
35+
k -= 1;
36+
}
37+
i = j;
38+
}
39+
reversed.iter().collect()
40+
}
41+
}
42+
43+
#[cfg(test)]
44+
mod tests {
45+
use super::*;
46+
47+
#[test]
48+
fn test_example_1() {
49+
let input = "Let's take LeetCode contest".to_string();
50+
let output = "s'teL ekat edoCteeL tsetnoc".to_string();
51+
assert_eq!(Solution::reverse_words(input), output);
52+
}
53+
}

0 commit comments

Comments
 (0)