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
pub fn longest_common_prefix(strs: Vec<String>) -> String {
let mut prefix: Vec<u8> = vec![];
for idx_0 in 0..strs[0].len() {
let ch = strs[0].as_bytes()[idx_0];
for idx_n in 1..strs.len() {
if strs[idx_n].len() == idx_0 || ch != strs[idx_n].as_bytes()[idx_0] {
return String::from_utf8(prefix).unwrap();
}
}
prefix.push(ch);
}
String::from_utf8(prefix).unwrap()
}
#[cfg(test)]
mod tests {
use super::longest_common_prefix;
#[test]
fn test_longest_common_prefix() {
let res = longest_common_prefix(
vec!["abcd", "a", ""]
.iter()
.map(|s| s.to_string())
.collect::<Vec<String>>(),
);
assert_eq!(res, "");
let res = longest_common_prefix(
vec!["abcd", "a", "adc"]
.iter()
.map(|s| s.to_string())
.collect::<Vec<String>>(),
);
assert_eq!(res, "a");
}
}