-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlongest-common-prefix.rs
55 lines (47 loc) · 1.21 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
#![allow(dead_code, unused, unused_variables)]
fn main() {
assert_eq!(
"fl".to_string(),
Solution::longest_common_prefix(vec![
"flower".to_string(),
"flow".to_string(),
"flight".to_string()
])
);
assert_eq!(
"".to_string(),
Solution::longest_common_prefix(vec![
"dog".to_string(),
"racecar".to_string(),
"car".to_string()
])
);
}
struct Solution;
impl Solution {
pub fn longest_common_prefix(strs: Vec<String>) -> String {
if strs.is_empty() {
return "".to_string();
}
let (mut result, mut index) = (Vec::new(), 0usize);
loop {
if index >= strs[0].len() {
break;
}
let i = strs[0].as_bytes()[index];
let mut flag = false;
for j in strs.iter() {
if index >= j.len() || j.as_bytes()[index] != i {
flag = true;
break;
}
}
if flag {
break;
}
result.push(i);
index += 1;
}
String::from_utf8(result).unwrap()
}
}