-
Notifications
You must be signed in to change notification settings - Fork 0
/
longest-common-prefix.rs
62 lines (57 loc) · 1.45 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
struct Solution;
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
if strs.len() == 1 {
return strs[0].to_owned();
}
let mut ans = String::new();
let f = strs.first().unwrap().chars();
for (i, c) in f.enumerate() {
for cc in strs.iter().skip(1) {
// 任何不匹配的方式都直接中断
if let Some(k) = cc.chars().nth(i) {
if c != k {
return ans;
}
} else {
return ans;
}
}
ans.push(c);
}
ans
}
}
fn main() {
println!(
"{}",
Solution::longest_common_prefix(vec!["ab".to_string(), "a".to_string()])
);
}
#[cfg(test)]
mod tests {
use crate::Solution;
#[test]
fn test() {
assert_eq!(
Solution::longest_common_prefix(vec!["ab".to_string(), "a".to_string()]),
"a"
);
assert_eq!(
Solution::longest_common_prefix(vec![
"dog".to_string(),
"racecar".to_string(),
"car".to_string()
]),
""
);
assert_eq!(
Solution::longest_common_prefix(vec![
"flower".to_string(),
"flow".to_string(),
"floght".to_string()
]),
"flo"
);
}
}