20240421 Finished
This commit is contained in:
parent
f84124d26c
commit
ec7fc6a29e
|
@ -108,3 +108,4 @@ mod p134_gas_station;
|
|||
mod p135_candy;
|
||||
mod p42_trapping_rain_water;
|
||||
mod p58_length_of_last_word;
|
||||
mod p151_reverse_words_in_a_string;
|
41
src/problem/p151_reverse_words_in_a_string.rs
Normal file
41
src/problem/p151_reverse_words_in_a_string.rs
Normal file
|
@ -0,0 +1,41 @@
|
|||
/**
|
||||
* [151] Reverse Words in a String
|
||||
*/
|
||||
pub struct Solution {}
|
||||
|
||||
|
||||
// submission codes start here
|
||||
|
||||
impl Solution {
|
||||
pub fn reverse_words(s: String) -> String {
|
||||
let mut words = Vec::new();
|
||||
|
||||
for word in s.split(' ') {
|
||||
if word.len() != 0 {
|
||||
words.push(word);
|
||||
}
|
||||
}
|
||||
|
||||
let length = words.len();
|
||||
let mut result = String::from(words[length - 1]);
|
||||
|
||||
for i in (0..length - 1).rev() {
|
||||
result.push(' ');
|
||||
result.push_str(words[i]);
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
// submission codes end
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_151() {
|
||||
assert_eq!("blue is sky the".to_owned(), Solution::reverse_words("the sky is blue".to_owned()));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user