-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paths0014_longest_common_prefix.rs
More file actions
47 lines (42 loc) · 1.06 KB
/
s0014_longest_common_prefix.rs
File metadata and controls
47 lines (42 loc) · 1.06 KB
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
#![allow(unused)]
pub struct Solution {}
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
let mut strs = strs.iter();
if let Some(head) = strs.next().cloned() {
strs.fold(head, |head, tail| {
head
.chars()
.zip(tail.chars())
.take_while(|(l, r)| l == r)
.map(|(chr, _)| chr)
.collect()
})
} else {
"".into()
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_14() {
assert_eq!(
Solution::longest_common_prefix(vec![
"flower".to_string(),
"flow".to_string(),
"flight".to_string(),
]),
"fl".to_string()
);
assert_eq!(
Solution::longest_common_prefix(vec![
"dog".to_string(),
"racecar".to_string(),
"car".to_string(),
]),
"".to_string()
);
}
}