-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathlib.rs
99 lines (89 loc) · 2.74 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
struct Solution;
use std::collections::HashMap;
impl<'a> Solution {
pub fn ladder_length(begin_word: String, end_word: String, word_list: Vec<String>) -> i32 {
if begin_word == end_word {
return 1;
}
if !word_list.contains(&end_word) {
return 0;
}
let mut conversion: HashMap<String, Vec<&String>> = HashMap::new();
for word in word_list.iter() {
for i in 0..word.len() {
let mut s = word.clone();
s.replace_range(i..i + 1, "*");
match conversion.get_mut(&s) {
None => {
conversion.entry(s).or_insert(vec![word]);
}
Some(list) => {
list.push(word);
}
}
}
}
let mut queue: Vec<(&String, i32)> = vec![(&begin_word, 1)];
let mut visited: HashMap<&String, bool> = HashMap::new();
visited.insert(&begin_word, true);
while queue.len() > 0 {
let item = queue[0];
if *item.0 == end_word {
return item.1;
}
queue = queue[1..].to_vec();
let next_words = Solution::get_next(item.0, &conversion);
for word in next_words {
if visited.contains_key(word) {
continue;
}
queue.push((word, item.1 + 1));
visited.insert(word, true);
}
}
0
}
fn get_next(word: &String, conversion: &HashMap<String, Vec<&'a String>>) -> Vec<&'a String> {
let mut ret: Vec<&String> = Vec::new();
for i in 0..word.len() {
let mut s = word.clone();
s.replace_range(i..i + 1, "*");
if conversion.contains_key(&s) {
ret = vec![ret, conversion.get(&s).unwrap().to_vec()].concat();
}
}
ret
}
}
fn main() {
println!(
"{}",
Solution::ladder_length(
String::from("hit"),
String::from("cog"),
vec![
String::from("hot"),
String::from("dot"),
String::from("dog"),
String::from("lot"),
String::from("log"),
String::from("cog")
]
)
);
println!(
"{}",
Solution::ladder_length(
String::from("hit"),
String::from("cog"),
vec![
String::from("hot"),
String::from("dot"),
String::from("dog"),
String::from("lot"),
String::from("log")
]
)
);
println!("Hello, world!");
}