-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest_common_prefix.rs
47 lines (41 loc) · 1.08 KB
/
longest_common_prefix.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
pub fn longest_common_prefix(strs: Vec<String>) -> String {
if strs.len() == 0 {
return "".to_string();
}
let mut prefix = strs[0].clone();
for i in 1..strs.len() {
let mut j = 0;
while j < prefix.len() && j < strs[i].len() {
if prefix.chars().nth(j).unwrap() != strs[i].chars().nth(j).unwrap() {
break;
}
j += 1;
}
prefix = prefix[..j].to_string();
}
prefix
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_14() {
assert_eq!(
longest_common_prefix(vec![
String::from("flower"),
String::from("flow"),
String::from("flight")
]),
String::from("fl")
);
assert_eq!(
longest_common_prefix(vec![
String::from("dog"),
String::from("racecar"),
String::from("car")
]),
String::from("")
);
}
}
// Reference: https://leetcode.com/problems/longest-common-prefix/