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
use std::cmp;
pub fn longest_common_prefix(strings: Vec<&str>) -> &str {
if strings.is_empty() {
return "";
}
let str0 = strings[0];
let str0bytes = str0.as_bytes();
let mut len = str0.len();
for str in &strings[1..] {
len = cmp::min(len,
str.as_bytes()
.iter()
.zip(str0bytes)
.take_while(|&(a, b)| a == b)
.count());
}
&strings[0][..len]
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn empty_lcp() {
assert_eq!(longest_common_prefix(vec![]), "");
}
#[test]
fn single_lcp() {
assert_eq!(longest_common_prefix(vec!["ab"]), "ab");
}
#[test]
fn no_lcp() {
assert_eq!(longest_common_prefix(vec!["a", "b", "c"]), "");
}
#[test]
fn valid_lcp() {
assert_eq!(longest_common_prefix(vec!["aba", "abb", "abc"]), "ab");
}
#[test]
fn valid_is_shortest_lcp() {
assert_eq!(longest_common_prefix(vec!["aba", "ab", "abc"]), "ab");
}
}