Skip to content

Commit efa4ffd

Browse files
committed
Create 648-replace-words.rs
1 parent a0599e0 commit efa4ffd

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

648-replace-words.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
pub fn replace_words(dictionary: Vec<String>, sentence: String) -> String {
2+
let mut dictionary = dictionary;
3+
dictionary.sort_by(|a, b|a.len().cmp(&b.len()));
4+
let mut ret_vec = vec![];
5+
'outer: for word in sentence.split_ascii_whitespace() {
6+
for prefix in &dictionary {
7+
if word.starts_with(prefix) {
8+
ret_vec.push(prefix.clone());
9+
continue 'outer;
10+
}
11+
}
12+
ret_vec.push(word.to_string())
13+
}
14+
ret_vec.join(" ")
15+
}
16+
17+
fn main() {
18+
let dictionary = vec!["catt".to_string(), "cat".to_string(), "bat".to_string(), "rat".to_string()];
19+
let sentence = "the cattle was rattled by the battery".to_string();
20+
println!("{:?}", replace_words(dictionary, sentence));
21+
}

0 commit comments

Comments
 (0)