forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0014-longest-common-prefix.rs
43 lines (42 loc) · 1.11 KB
/
0014-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
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
if strs.len() == 0 {
return "".to_string();
}
if strs.len() == 1 {
return strs[0].clone();
}
if strs[0].len() == 0 {
return "".to_string();
}
let mut common = String::new();
let mut same = true;
let mut i = 0;
while same {
let common_char = match strs[0].chars().nth(i) {
Some(c) => {
common.push(c);
c
}
None => return common,
};
for s in &strs {
if let Some(c) = s.chars().nth(i) {
if c != common_char {
same = false;
break;
}
} else {
same = false;
break;
}
}
i += 1;
}
if common.len() > 0 {
common[..common.len() - 1].to_string()
} else {
common
}
}
}