Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit af729c0

Browse files
committed
solve #151
1 parent 9abfdaa commit af729c0

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,4 @@ mod n0147_insertion_sort_list;
145145
mod n0148_sort_list;
146146
mod n0149_max_points_on_a_line;
147147
mod n0150_evaluate_reverse_polish_notation;
148+
mod n0151_reverse_words_in_a_string;
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/**
2+
* [151] Reverse Words in a String
3+
*
4+
* Given an input string, reverse the string word by word.
5+
*
6+
*
7+
*
8+
* Example 1:
9+
*
10+
*
11+
* Input: "the sky is blue"
12+
* Output: "blue is sky the"
13+
*
14+
*
15+
* Example 2:
16+
*
17+
*
18+
* Input: " hello world! "
19+
* Output: "world! hello"
20+
* Explanation: Your reversed string should not contain leading or trailing spaces.
21+
*
22+
*
23+
* Example 3:
24+
*
25+
*
26+
* Input: "a good example"
27+
* Output: "example good a"
28+
* Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.
29+
*
30+
*
31+
*
32+
*
33+
* Note:
34+
*
35+
*
36+
* A word is defined as a sequence of non-space characters.
37+
* Input string may contain leading or trailing spaces. However, your reversed string should not contain leading or trailing spaces.
38+
* You need to reduce multiple spaces between two words to a single space in the reversed string.
39+
*
40+
*
41+
*
42+
*
43+
* Follow up:
44+
*
45+
* For C programmers, try to solve it in-place in O(1) extra space.
46+
*/
47+
pub struct Solution {}
48+
49+
// submission codes start here
50+
51+
impl Solution {
52+
pub fn reverse_words(mut s: String) -> String {
53+
let mut seq = s.trim().chars().collect::<Vec<_>>();
54+
seq.reverse();
55+
let mut start_idx = 0_usize;
56+
let mut i = 0_usize;
57+
while i < seq.len() {
58+
if seq[i] == ' ' {
59+
if i == start_idx {
60+
seq.remove(i);
61+
continue;
62+
}
63+
seq[start_idx..i].reverse();
64+
start_idx = i + 1;
65+
}
66+
i += 1;
67+
}
68+
seq[start_idx..].reverse();
69+
seq.into_iter().collect()
70+
}
71+
}
72+
73+
// submission codes end
74+
75+
#[cfg(test)]
76+
mod tests {
77+
use super::*;
78+
79+
#[test]
80+
fn test_151() {
81+
assert_eq!(Solution::reverse_words("the sky is blue".to_owned()), "blue is sky the".to_owned());
82+
assert_eq!(Solution::reverse_words(" hello world! ".to_owned()), "world! hello".to_owned());
83+
}
84+
}

0 commit comments

Comments
 (0)